【问题标题】:Run Commands continuously and step by step based on previous command output in JSch根据 JSch 中先前的命令输出连续并逐步运行命令
【发布时间】:2022-02-26 15:54:30
【问题描述】:

我想在我的应用程序中实现一个东西,比如 putty 或 mobaxterm。我希望用户 ssh 到服务器,然后运行命令并在其上执行操作。我使用 ChannelExec 但运行任何命令后它会断开通道并进入第一步.例如,我想运行 ls 然后将结果返回给用户,然后用户 cd 进入一个目录,然后运行 ​​ls 并查看该目录中的内容。 这个应该怎么实现?

【问题讨论】:

  • 我以前见过他们。他们没有帮助我。答案没有帮助。但是感谢@MartinPrikryl
  • 你的问题在哪里说,你已经尝试过一些东西,为什么它没有特别帮助你? “答案没有帮助” 并没有告诉我们任何事情。 + 如果不出意外,链接的问题至少应该清楚表明您应该使用“shell”通道而不是“exec”。
  • 我之前使用过 shell 通道。shell 通道没有执行我的命令,也没有返回命令的响应,我真的很困惑,执行命令但没有保存状态,shell 只是将我的命令添加到服务器并没有执行它@Martin prikryl

标签: java ssh jsch


【解决方案1】:

在与代码和文档苦苦挣扎 1 个月后,我找到了答案。

我想在企业应用程序中实现 ssh。首先我要说,如果你想要交互行为,你应该使用“shell”,因为它可以给出你的命令并返回答案并保持与服务器的连接,但之后是“exec”执行命令关闭通道。然后我将输出和输入定义为类变量。这是我的类:

@服务 公共类 SshService {

private Channel channel;
private Session session;
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();

PipedInputStream pip = new PipedInputStream(40);
PipedOutputStream pop = new PipedOutputStream(pip);
PrintStream print = new PrintStream(pop);

public SshService() throws IOException {
}

public String sshConnectToOlt(String username, String password, String host, int port) throws Exception {

    session = new JSch().getSession(username, host, port);
    session.setPassword(password);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect(30000);

    channel = session.openChannel("shell");

    channel.setInputStream(pip);

    responseStream= new ByteArrayOutputStream();
    channel.setOutputStream(responseStream);

    channel.connect(3 * 1000);

    Thread.sleep(2000);

    return responseStream.toString();

}

public String sshToOltCommands(String command) throws Exception {
    print.println(command);

    Thread.sleep(2000);

    String response = responseStream.toString();
    return response.replaceAll("\u001B\\[[\\d;]*[^\\d;]","");
}

public void disconnectFromOlt() {
    this.channel.disconnect();
    this.session.disconnect();
}

}

我写了 3 个方法。 sshConnectToOlt:用于连接服务器 sshToOltCommands : 在服务器上执行命令 disconnectFromOlt : 与服务器断开连接

注意

我用过

response.replaceAll("\u001B\\[[\\d;]*[^\\d;]","");

从响应中删除 ANSI 控制字符 (VT100)

【讨论】:

    猜你喜欢
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2023-03-23
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多