inputstream使程序等待

时间:2015-07-29 08:11:57

标签: java j2ssh

我正在使用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));
                }

2 个答案:

答案 0 :(得分:0)

最后我找到了答案,谢谢你,mangusta。

我在套接字上添加了超时。有效。我刚在程序中添加了以下行,

transport.setSoTimeout(3000);

答案 1 :(得分:0)

您的代码将继续在会话InputStream上循环,直到会话关闭,即InputStream返回EOF。当您使用startShell方法时,会生成一个交互式shell,因此会话将继续并在您的命令执行后呈现一个新提示,等待另一个命令。

您可以在命令中添加对退出的调用

String command = "ps -ef | grep " + port + ';exit\n';

或者您可以在会话中使用备用executeCommand方法,而不是将命令写出到OutputStream。

session.executeCommand(command);