我有一个程序,可以ssh
进入远程主机,然后远程执行命令。像mkdir
和cd
这样的命令可以工作,但是当我尝试执行命令sudo su - username
时,程序只是挂起。我想知道在我的代码中是否有任何遗漏/错误。执行sudo su命令后Java程序挂起?
JSch jSch = new JSch();
Channel channel = null;
Session session = null;
InputStream in = null;
String username;
OutputStream os = null;;
try {
Properties conf = new Properties();
conf.put("StrictHostKeyChecking", "no");
jSch.addIdentity("id_rsa");
jSch.setConfig(conf);
session = jSch.getSession("username", "hostname", 22);
String cmd = "mkdir test";
session.connect(); // creating the ssh connection
channel = (ChannelExec) session.openChannel("exec");
((ChannelExec)channel).setCommand(cmd);
channel.setInputStream(null);
in = channel.getInputStream(null);
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
}
if (channel.isClosed()) {
break;
}
try {
Thread.sleep(1000); // to wait for long running process ..
} catch (Exception ee) {
}
String value = new String(tmp);
System.out.println("input stream " + value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
channel.disconnect();
session.disconnect();
if(in!=null)
in.close();
}
而且,我需要ssh
从该主机到另一台主机后,我sudo
,所以基本上我通过网关之类的事情需要ssh
到远程主机上,然后连接到一个数据库,一旦这个问题得到修复。
在此任何灯将不胜感激。
谢谢。
http://serverfault.com/questions/107187/sudo-su-username-while-keeping-ssh- key-forwarding – blearn
你有一个'catch'什么也不做,为什么不打印堆栈跟踪,因为它可能是一个可能导致“我的程序挂起”,并且你没有捕获到提出的错误 –
本程序执行后挂起sudo su - username命令..对于那个 – dehsams123