如何应对交互式Linux命令

如何应对交互式Linux命令

本文介绍了如何应对交互式Linux命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code这让我通过ssh连接,运行一个命令,并得到响应返回。它工作正常,但只适用于非交互式命令(如: LS 东风这后给出结果回来马上其运行)。问题是,当我试图运行像 passwd文件 code是永远等待一些交互式命令为响应(当然越来越都不)。

如何应对交互命令?我真的不关心产出,我只是想运行它。

公共字符串runCommand(字符串命令)抛出异常{    // SSH通道
    ChannelExec channelssh =(ChannelExec)session.openChannel(EXEC);    //执行命令
    channelssh.setCommand(命令);
    channelssh.connect();    为InputStream的InputStream = channelssh.getInputStream();
    的BufferedReader的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream的));
    StringBuilder的StringBuilder的=新的StringBuilder();
    串线;    而((行= bufferedReader.readLine())!= NULL)
    {
        stringBuilder.append(线);
        stringBuilder.append('\\ n');
    }    channelssh.disconnect();
    返回stringBuilder.toString();
}


解决方案

1,您可以使用ChannelShell。这里有一个例子:。和这个职位澄清exec和外壳之间的差异:what's jsch ChannelExec和ChannelShell之间的确切区别?

2,我试过ChannelExec.setPty(真)。并以这种方式,我能得到的输出。然而,它并没有停止。

I have code which allow me to connect through ssh, run a command and get response back. It works fine but only for the non-interactive commands (like: ls, df which gives the result back immediately after their run). The problem is when I'm trying to run some interactive command like top or passwd code is waiting forever for the response (and of course getting none).

How to cope with interactive commands? I really don't care about the output, I just wanna to run it.

public String runCommand(String command)  throws Exception {

    // SSH Channel
    ChannelExec channelssh = (ChannelExec) session.openChannel("exec");

    // Execute command
    channelssh.setCommand(command);
    channelssh.connect();

    InputStream inputStream = channelssh.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder stringBuilder = new StringBuilder();
    String line;

    while ((line = bufferedReader.readLine()) != null)
    {
        stringBuilder.append(line);
        stringBuilder.append('\n');
    }

    channelssh.disconnect();
    return stringBuilder.toString();
}
解决方案

1, You can use ChannelShell. Here is an example: Shell.java. And this post clarify differences between exec and shell: what's the exact differences between jsch ChannelExec and ChannelShell?

2, I tried ChannelExec.setPty(true). And in this way, I could get output. However, it didn't stop.

这篇关于如何应对交互式Linux命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:33