在unixshell中使用JAVA拦截Jsch提示输入密码
我正在尝试使用java程序使用jsch运行shell命令。 命令需要sudo访问才能执行。下面是我的代码示例在unixshell中使用JAVA拦截Jsch提示输入密码,java,shell,unix,sudo,su,Java,Shell,Unix,Sudo,Su,我正在尝试使用java程序使用jsch运行shell命令。 命令需要sudo访问才能执行。下面是我的代码示例 String command1="sudo restart oraserv"; java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session
String command1="sudo restart oraserv";
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session;
try {
session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel=session.openChannel("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
((ChannelExec)channel).setPty(true);
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
} catch (JSchException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在这一切都没有发生后,我想让它运行而不提示输入密码。
我有没有办法为它提供成功执行的密码。JSCH网站为您提供了一个关于这个问题的答案。想法是将密码写入
OutputStream
,它表示ssh连接的“写入”端。
相关代码块:
((ChannelExec)channel).setCommand("sudo -S -p '' "+command);
InputStream in=channel.getInputStream();
OutputStream out=channel.getOutputStream();
((ChannelExec)channel).setErrStream(System.err);
channel.connect();
out.write((sudo_pass+"\n").getBytes());
out.flush();
((ChannelExec)channel).setCommand("sudo -S -p '' "+command);
InputStream in=channel.getInputStream();
OutputStream out=channel.getOutputStream();
((ChannelExec)channel).setErrStream(System.err);
channel.connect();
out.write((sudo_pass+"\n").getBytes());
out.flush();