javalinuxjsch

How to show only the result when running Linux command in Java?


I am using JSch to run some command in remote Linux box.

session = jsch.getSession(user, "host", 1222);
...
Channel shellChannel = session.openChannel("shell");
OutputStream ops = shellChannel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);

ps.println("pwd");
InputStream in = shellChannel.getInputStream();
...
//print the char stream from 'in' using something similar to 
//http://stackoverflow.com/questions/9126142/output-the-result-of-a-bash-script#

However, the printout of the result from inputStream contains everything, including user prompt, my original command (pwd in this case), and the result /u02/app2/bbisit:

bbisit@sdvdbres016$ 
bbisit@sdvdbres016$ pwd
/u02/app2/bbisit

But all I really want is the real output of the command, i.e. /u02/app2/bbisit.

Is there a way to get only the actual result of the command, but not the other garbage.


Solution

  • Use the "exec" channel, not the "shell" channel.

    The "exec" channel is intended for automating command execution. The "shell" channel is intended for implementing an interactive shell.

    See https://web.archive.org/web/20241207183201/http://www.jcraft.com/jsch/examples/Exec.java.html