使用JSch执行命令时未获得任何输出

问题描述 投票:0回答:1

我试图先使用JSch在远程系统中执行sudo su - user命令,然后连续执行管道外壳程序命令。我想将命令输出读入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());
linux shell ssh jsch
1个回答
1
投票

您在命令末尾缺少“ 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

检查官方JSch Exec.java示例:http://www.jcraft.com/jsch/examples/Exec.java.html

© www.soinside.com 2019 - 2024. All rights reserved.