如何用Java编写ssh的stdin? [英] How to write in Java to stdin of ssh?

查看:89
本文介绍了如何用Java编写ssh的stdin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一切在命令行上都可以正常工作,但是当我将所需内容转换为Java时,接收过程将永远不会在stdin上得到任何东西.

Everything works fine on the command line, but when I translate what I want into Java, the receiving process never gets anything on stdin.

这就是我所拥有的:

private void deployWarFile(File warFile, String instanceId) throws IOException, InterruptedException {
    Runtime runtime = Runtime.getRuntime();
    // FIXME(nyap): Use Jsch.
    Process deployWarFile = runtime.exec(new String[]{
            "ssh",
            "gateway",
            "/path/to/count-the-bytes"});

    OutputStream deployWarFileStdin = deployWarFile.getOutputStream();
    InputStream deployWarFileStdout = new BufferedInputStream(deployWarFile.getInputStream());
    InputStream warFileInputStream = new FileInputStream(warFile);

    IOUtils.copy(warFileInputStream, deployWarFileStdin);
    IOUtils.copy(deployWarFileStdout, System.out);

    warFileInputStream.close();
    deployWarFileStdout.close();
    deployWarFileStdin.close();

    int status = deployWarFile.waitFor();
    System.out.println("************ Deployed with status " + status + " file handles. ************");
}

脚本字节计数"很简单:

The script 'count-the-bytes' is simply:

#!/bin/bash

echo "************ counting stdin bytes ************"
wc -c
echo "************ counted stdin bytes ************"

输出表明该函数挂在'wc -c'行-永远不会到达'counted stdin bytes'行.

The output indicates that the function hangs at the 'wc -c' line -- it never gets to the 'counted stdin bytes' line.

这是怎么回事?使用Jsch会有所帮助吗?

What's going on? Would using Jsch help?

推荐答案

在期望wc -c返回之前,您可以尝试关闭输出流.

You might try closing the output stream before you expect wc -c to return.

IOUtils.copy(warFileInputStream, deployWarFileStdin);
deployWarFileStdin.close();
IOUtils.copy(deployWarFileStdout, System.out);

warFileInputStream.close();
deployWarFileStdout.close();

这篇关于如何用Java编写ssh的stdin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆