1

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 Answer 1

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:
https://web.archive.org/web/20241207183201/http://www.jcraft.com/jsch/examples/Exec.java.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.