【问题标题】:Getting output from ssh with BufferedReader使用 BufferedReader 从 ssh 获取输出
【发布时间】:2018-02-04 10:23:05
【问题描述】:

我正在使用以下脚本来执行命令并获取输出: 运行时 rt = Runtime.getRuntime();

static Runtime rt;
static Process proc;

public static void main(String[] Args) throws IOException, InterruptedException {

    rt = Runtime.getRuntime();
        String[] commands = {"ssh.exe","-o BatchMode=yes",  "root@192.168.1.1", "cat /var/a.txt"};
    //  String[] commands = {"ssh.exe", "root@192.168.0.1"};
    //  String[] commands = { "ls", "-la" };

    proc = rt.exec(commands);

    new Thread("out") {
        public void run() {
            System.out.println("Thread: " + getName() + " running");
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            String s = null;
            // read the output from the command
            System.out.println("StdOut:\n");
            try {
                while ((s = stdInput.readLine()) != null) {
                    System.out.println("$ " + s);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }.start();

    new Thread("err") {
        public void run() {
            System.out.println("Thread: " + getName() + " running");
            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

            String s = null;
            // read any errors from the attempted command
            System.out.println("StdErr:\n");
            try {
                while ((s = stdError.readLine()) != null) {
                    System.out.println("! " + s);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }.start();




    Thread.sleep(10000);
    System.out.println("end");

}

如果我执行“ls -la”或“ssh”,我会得到预期的输出。但是,尝试从远程设备(第 1 行)获取 a.txt 内容失败并且操作挂起。 从命令行执行“ssh root@192.168.0.1 cat a.txt”可以工作并检索内容。

为什么会这样?如何修复? 谢谢

【问题讨论】:

    标签: java ssh bufferedreader


    【解决方案1】:

    因为您需要在单独的线程中读取两个流,或者将它们合并。您不能假设该进程将退出并因此关闭其stderr,然后再向stdtout 写入任何内容,或者更确切地说,向stdout 写入的内容很少以至于它不会阻塞。

    【讨论】:

    • 更新问题中的代码,向我们展示您是如何做到的。
    • 您可能还需要关闭进程的输入流。
    猜你喜欢
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2015-10-28
    • 2015-05-09
    • 2013-06-27
    • 1970-01-01
    • 2014-08-31
    • 2012-06-07
    相关资源
    最近更新 更多