linux - 使用 JSch 执行命令时没有得到任何输出

标签 linux shell ssh jsch

我尝试先使用 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” channel 来执行命令。使用“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

关于linux - 使用 JSch 执行命令时没有得到任何输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31844192/

相关文章:

linux - 使用 Cron Job 检查我的 mod_wsgi/apache 服务器是否正在运行并重新启动

python - 如何使用python子进程使用shell'source'命令

javascript - Testrpc 错误:在 Mac 上监听 EADDRINUSE:::8545

github - 为 nginx 用户添加 SSH-Key (for github)

java - 如何使用 JMX 客户端列出所有 MBean

c - 在 ubuntu 12.04 上制作 openwsman 时出错

php - 在 xampp 错误上通过 php 执行 shell

java - 从 Web 应用程序执行需要 sudo 的 shell 脚本

ssh - 使用 SSH key 进行 http 用户验证

python - Paramiko/加密弃用警告 : CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers