我使用J2ssh库连接到Unix机器,运行一个命令,并使用输入流得到结果。但是程序在读取输入流的时候进入了循环。我能够从输入蒸汽中得到结果,但是程序在那里停止了,没有继续。为什么程序会卡在那个循环里?
下面是源代码。
public void loginAndCheckProcess(String hostName, String userName, String password, String port) {
try {
SshConnector con = SshConnector.createInstance();
SocketTransport transport = new SocketTransport(hostName, 22);
transport.setTcpNoDelay(true);
SshClient client = con.connect(transport, userName);
Ssh2Client ssh2 = (Ssh2Client) client;
PasswordAuthentication pwd = new PasswordAuthentication();
do {
pwd.setPassword(password);
} while (ssh2.authenticate(pwd) != SshAuthentication.COMPLETE && client.isConnected());
String command = "ps -ef | grep " + port + '\n';
if (client.isAuthenticated()) {
SshSession session = client.openSessionChannel();
session.startShell();
session.getOutputStream().write(command.getBytes());
InputStream is = session.getInputStream();
Scanner br = new Scanner(new InputStreamReader(is));
String line = null;
int isRunning = 0;
while (br.hasNextLine()) {
line = br.nextLine();
isRunning++;
System.out.println(line);
}
session.close();
}
} catch (SshException | IOException | ChannelOpenException ex) {
Logger.getLogger(Authenticator.class.getName()).log(Level.SEVERE, null, ex);
}
}
我试着用下面的循环替换上面的第二个while循环,但没有成功。
try (Reader in = new InputStreamReader(is, "UTF-8")) {
for (;;) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
}
System.out.println(out);
并与下面的循环,但没有运气。
byte[] tmp = new byte[1024];
while (is.available() > 0) {
int i = is.read(tmp, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(tmp, 0, i));
}
我终于找到了答案,谢谢你mangusta。
我在socket上加了超时。它的工作。我只是在程序中添加了以下一行。
transport.setSoTimeout(3000);
你的代码会一直在会话InputStream上循环,直到会话关闭,即InputStream返回EOF。由于你使用了startShell方法,这将产生一个交互式的shell,所以会话将继续,并在你的命令执行后呈现一个新的提示,等待另一个命令。
你可以在你的命令中添加一个退出的调用。
String command = "ps -ef | grep " + port + ';exit\n';
或者你可以在会话中使用另一种方法executeCommand,而不是将命令写到OutputStream中。
session.executeCommand(command);