在sshj中执行命令序列


问题内容

我需要使用sshj库通过ssh在远程服务器上执行一些命令序列。

我做

        Session session = ssh.startSession();
        Session.Command cmd = session.exec("ls -l");
        System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
        cmd.join(10, TimeUnit.SECONDS);
        Session.Command cmd2 = session.exec("ls -a");
        System.out.println(IOUtils.readFully(cmd2.getInputStream()).toString());

它把我扔了

net.schmizz.sshj.common.SSHRuntimeException:该会话通道已全部用尽

但是我无法为每个命令重新创建会话,因为此示例将显示主目录列表,但不显示/ some / dir列表。


问题答案:

您可以考虑使用类似Expect的第三方库,该库简化了使用远程服务和捕获输出的过程。这些库旨在执行一系列命令。您可以尝试以下一组不错的选择:

但是,当我要解决类似的问题时,我发现这些库已经很旧了。它们还引入了很多不需要的依赖项。因此,我创建了自己的,并提供给其他人。它称为ExpectIt。我的图书馆的优势在项目主页上有所说明。您可以尝试一下。

这是一个使用sshj与公共远程SSH服务进行交互的示例:

    SSHClient ssh = new SSHClient();
    ...
    ssh.connect("sdf.org");
    ssh.authPassword("new", "");
    Session session = ssh.startSession();
    session.allocateDefaultPTY();
    Shell shell = session.startShell();
    Expect expect = new ExpectBuilder()
            .withOutput(shell.getOutputStream())
            .withInputs(shell.getInputStream(), shell.getErrorStream())
            .build();
    try {
        expect.expect(contains("[RETURN]"));
        expect.sendLine();
        String ipAddress = expect.expect(regexp("Trying (.*)\\.\\.\\.")).group(1);
        System.out.println("Captured IP: " + ipAddress);
        expect.expect(contains("login:"));
        expect.sendLine("new");
        expect.expect(contains("(Y/N)"));
        expect.send("N");
        expect.expect(regexp(": $"));
        expect.send("\b");
        expect.expect(regexp("\\(y\\/n\\)"));
        expect.sendLine("y");
        expect.expect(contains("Would you like to sign the guestbook?"));
        expect.send("n");
        expect.expect(contains("[RETURN]"));
        expect.sendLine();
    } finally {
        session.close();
        ssh.close();
        expect.close();
    }

这是完整可行示例的链接。