【问题标题】:Not getting any output when using JSch to execute commands使用 JSch 执行命令时没有得到任何输出
【发布时间】:2015-10-28 22:03:07
【问题描述】:

我正在尝试使用 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());

【问题讨论】:

    标签: linux shell ssh jsch


    【解决方案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

    查看官方JSchExec.java例子:
    http://www.jcraft.com/jsch/examples/Exec.java.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 2016-10-21
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多