我正在使用java ssh客户端(http://www.jcraft.com/jsch/)连接到远程计算机并执行命令。代码工作正常,直到我连接到远程机器并执行命令。但问题是,即使命令执行成功,通道和会话也不会断开连接。
我也调用了session.disconnect和channel.disconnect,但问题仍然存在。
这是我的代码:
JSch jsch = new JSch();
String privateKey = "C:\\test\\key";
jsch.addIdentity(privateKey);
String host = null;
host = "192.168.102.211";
Session session = jsch.getSession("chef-admin", host, 22);
Channel channel = session.openChannel("shell");
try
{
String cmd = "sudo su";
String command = "chef-client";
UserInfo ui = new MyUserInfo() {
public boolean promptYesNo(String message) {
return true;
}
};
session.setUserInfo(ui);
session.connect(30000);
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);
channel.connect();
ps.println(cmd);
ps.println(command);
ps.close();
InputStream in = channel.getInputStream();
byte[] bt = new byte[1024];
while (in.available() > 0) {
int i = in.read(bt, 0, 1024);
if (i < 0)
break;
String str = new String(bt, 0, i);
System.out.println("valueeeeeeeeeeeeeeee is " + i);
System.out.print(str);
}
System.out.println("before channel");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (channel != null) {
System.out.println("finally");
channel.disconnect();
session.disconnect();
System.out.println(channel.isConnected());
}
}