Not getting any output when using JSch to execute commands

走远了吗. 提交于 2020-02-23 04:03:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!