我正在使用testng运行测试用例。此测试用例使用Jsch尝试将ssh命令发送到远程计算机。 Jsch函数应该从命令返回输出(包括任何异常)。但是,即使存在超时异常,我也无法查看输出和测试通过!
这是JSch函数:
public static String sshCommand (String username, String password, String host, int port, String command) {
StringBuilder outputBuffer = new StringBuilder();
try {
System.out.println("about to send command: " + command);
JSch jschSSHChannel = new JSch();
Session session=jschSSHChannel.getSession(username, host, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
InputStream commandOutput = channel.getInputStream();
channel.connect();
int readByte = commandOutput.read();
while(readByte != 0xffffffff)
{
outputBuffer.append((char)readByte);
readByte = commandOutput.read();
}
channel.disconnect();
session.disconnect();
} catch (Exception e) {
System.out.println("Exception encountered returning: " + e.toString());
return e.toString();
}
return outputBuffer.toString();
}
这是评估ssh函数输出的代码:
String output = jschClass.sshCommand("username", "password", ipAddress, 22, command);
System.out.println("Command output: " + output);
Assert.assertTrue(!output.contains("Exception"));
System.out.println("Test complete");
问题是我从未看到System.out.println("Command output: " + output);
打印出来。它会跳过该语句并在退出之前执行System.out.println("Test complete");
。
此外,我在sshcommand函数中放置的catch语句似乎永远不会执行。显示异常,但它似乎没有执行我编写的代码。事实上,这几乎就是异常来自其他地方。这是我在程序输出中看到的内容:
about to send command: ping -c 5 google.com
com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused: connect
Test complete
at com.jcraft.jsch.Util.createSocket(Util.java:349)
at com.jcraft.jsch.Session.connect(Session.java:215)
at com.jcraft.jsch.Session.connect(Session.java:183)
at com.cisco.ui2.openstack.jsch.JschHelper.sshCommand(JschHelper.java:28)
at com.cisco.ui2.openstack.PingPublicSite.createImageAndPingPublicSite(PingPublicSite.java:91)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[removed for space]
at com.jcraft.jsch.Util.createSocket(Util.java:343)
... 28 more
知道发生了什么事吗?