ssh到远程主机使用sshpass并使用java获取结果

时间:2017-07-13 10:01:09

标签: java linux sshpass

我尝试在远程计算机上运行某些命令并使用Java捕获结果。我有一个名为test.sh的shell脚本,它有以下命令:

sshpass -p 'password' ssh root@host.com echo hostname

我使用以下java代码运行它:

public void runCommand() throws IOException, InterruptedException {

    ProcessBuilder builder = new ProcessBuilder();
    boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
    if (isWindows) {
        builder.command("cmd.exe", "/c", "dir");
    } else {
        builder.command("sh", "-c", "sh test.sh");
    }
    builder.directory(new File(System.getProperty("user.home")));
    Process process;
    BufferedReader reader = null;
    try {
        process = builder.start();
        reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        String output = stringBuilder.toString();
        System.out.println(output);
    } finally

    {
        if (reader != null)
            try {
                reader.close();
            } catch (IOException e) {
            }
    }
}

命令执行但我没有在输出中得到任何东西。如果我使用像echo,hostname这样的简单命令,那么我就可以在输出中得到结果。我知道JSch可以解决问题,但我无法使用它。

1 个答案:

答案 0 :(得分:2)

在Java中启动Process时,必须将stdout和stderr都消耗到avoid blocking,并且应该记录或控制两者(避免消费丢弃)。现在使用ProcessBuilder提供了比链接文章提到的更简单的解决方案。

在这种情况下,您完全忽略命令的错误输出。您说您的进程退出状态代码为127,因此它可能会在stderr上打印,因此您将使用ProcessBuilder.redirectErrorStream(true)获取有关错误的更多详细信息。

对于您的java进程,可能没有安装或安装sshpass但不在$PATH中。

相关问题