使用 JSch 执行命令时没有得到任何输出
Not getting any output when using JSch to execute commands
我尝试使用 JSch 首先在远程系统中执行 sudo su - user
命令,然后连续执行管道 shell 命令。我想将命令输出读入 String
。我怎样才能做到这一点?我正在尝试这样的事情,但无法获得任何输出。请指教
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());
您在命令末尾缺少 "Enter"(换行符)。
所以它们实际上从不执行,这就是为什么您无法获得任何输出的原因。
String sudoCommand = "sudo su - " + sudoAs + "\n";
String nextCommand = "ps -eaf | grep user | wc -l\n";
虽然一般来说,您不应该使用 "shell" 通道来执行命令。使用 "exec" 命令。
参见 What is the difference between the 'shell' channel and the 'exec' channel in JSch
查看官方JSchExec.java
示例:
http://www.jcraft.com/jsch/examples/Exec.java.html
我尝试使用 JSch 首先在远程系统中执行 sudo su - user
命令,然后连续执行管道 shell 命令。我想将命令输出读入 String
。我怎样才能做到这一点?我正在尝试这样的事情,但无法获得任何输出。请指教
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());
您在命令末尾缺少 "Enter"(换行符)。
所以它们实际上从不执行,这就是为什么您无法获得任何输出的原因。
String sudoCommand = "sudo su - " + sudoAs + "\n";
String nextCommand = "ps -eaf | grep user | wc -l\n";
虽然一般来说,您不应该使用 "shell" 通道来执行命令。使用 "exec" 命令。
参见 What is the difference between the 'shell' channel and the 'exec' channel in JSch
查看官方JSchExec.java
示例:
http://www.jcraft.com/jsch/examples/Exec.java.html