问题
I am trying to use JSch to execute sudo su - user
command in a remote system first and then consecutively execute a piped shell command. I would like to read the command output into a String
. How can I do this? I was trying something like this but could not get any output. Please advice.
session = getSession();
channel = (ChannelShell)session.openChannel( "shell" );
String sudoCommand = "sudo su - " + sudoAs;
String nextCommand = "ps -eaf | grep user | wc -l";
pipeIn = new PipedInputStream();
pipeOut = new PipedOutputStream( pipeIn );
channel.setInputStream(pipeIn);
channel.setOutputStream(System.out, true);
channel.connect(3*1000);
pipeOut.write(sudoCommand.getBytes());
Thread.sleep(1000);
pipeOut.write(nextCommand.getBytes());
回答1:
You are missing "Enter" (new-line) at the end of the commands.
So they actually never execute, that's why you cannot get any output.
String sudoCommand = "sudo su - " + sudoAs + "\n";
String nextCommand = "ps -eaf | grep user | wc -l\n";
Though in general, you should not use the "shell" channel to execute commands. Use the "exec" command.
See What is the difference between the 'shell' channel and the 'exec' channel in JSch
Check the official JSch Exec.java
example:
http://www.jcraft.com/jsch/examples/Exec.java.html
来源:https://stackoverflow.com/questions/31844192/not-getting-any-output-when-using-jsch-to-execute-commands