运行 根据JSch 中先前的命令输出,连续并逐步执行命令

Run Commands continuously and step by step based on previous command output in JSch

我想在我的应用程序中实现一个类似 putty 的东西,或者 mobaxterm.i 希望用户通过 ssh 连接到服务器然后 运行 命令并在 that.i 上执行操作使用 ChannelExec 但在 运行 任何命令都会断开通道并转到第一个 step.for 示例,我想 运行 ls 然后 return 结果给用户然后用户 cd 到一个目录然后 运行 ls 并查看该目录中的内容。 应该如何实施?

经过 1 个月的代码和文档研究后,我找到了答案。

我想在企业中实现 ssh application.first 如果你想要交互行为,你应该使用“shell”,因为它可以给你命令 return 回答并保持与服务器的连接,但在执行命令关闭后“exec” channel.then 我将输出和输入定义为 class variables.this 是我的 class:

@服务 public class 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)