Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write in Java to stdin of ssh?

Tags:

java

ssh

stdin

pipe

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

Here's what I have:

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 ************"

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

What's going on? Would using Jsch help?

like image 870
Noel Yap Avatar asked Jun 20 '11 17:06

Noel Yap


1 Answers

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();
like image 137
antlersoft Avatar answered Sep 24 '22 19:09

antlersoft