javasshstdoutjsch

Capture server command output using JSch and Java


I am using JSch to ssh to multiple servers and run few commands. My output file capture everything. But I am looking for a way to capture only the server respond.

Code:

try (OutputStream log = new BufferedOutputStream( new FileOutputStream("OUTPUT_FILE"))) {
    JSch jsch = new JSch();

    for (String host : jssh.listOfhost()) {
        Session session = jsch.getSession(user, host, 22);
        session.setPassword(password);
        session.setConfig(getProperties());
        session.connect(10 * 1000);

        Channel channel = session.openChannel("shell");
        channel.setOutputStream(log, true);

        try (PipedInputStream commandSource = new PipedInputStream();
             OutputStream commandSink = new PipedOutputStream(commandSource)) {

            CommandSender sender = new CommandSender(commandSink);
            Thread sendThread = new Thread(sender);
            sendThread.start();

            channel.setInputStream(commandSource);
            channel.connect(15 * 1000);

            sendThread.join();
            if (sender.exception != null) {
                throw sender.exception;
            }
        }

        channel.disconnect();
        session.disconnect();
    }
}

Current Output:

Last login: Thu Jan 14 15:06:17 2016 from 192.168.1.4
mypc:~ user$ 
mypc:~ user$ hostname
mypc
mypc:~ user$ df -l | grep disk0s3 |tr -s [:blank:]|cut -d ' ' -f 7
19098537

but I only want to output the following

mypc 19098537

Which is an outcome of the following two commands

hostname
df -l | grep disk0s3 |tr -s [:blank:]|cut -d ' ' -f 7

Solution

  • Use exec channel, not shell channel. The exec channel is intended for command execution. The shell channel is intended for implementing an interactive session. That's why you get all the prompts and such. You do not get these in the exec channel.

    See the official JSCh example for using exec channel.

    If you need to read both stdout and stderr, see my answer to How to read JSch command output?