本文介绍了在 sshj 中执行命令序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to execute some sequence of commands at the remote server via ssh, using sshj library.

我愿意

        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 列表.

But I can't recreate session for every single command, because this example it will show home directory list, but not the /some/dir list.

推荐答案

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

You can consider using an Expect-like third party library which simplifies working with remote services and capturing output. Those libraries are designed to execute a sequence of commands. Here is a good set of options you can try:

然而,当我要解决类似的问题时,我发现这些库相当陈旧.它们还引入了许多不需要的依赖项.所以我创建了我自己的并提供给其他人.它被称为 ExpectIt.我的图书馆的优势在项目主页上有说明.你可以试试看.

However, when I was about to solve similar problem I found these libraries are rather old. They also introduce a lot of unwanted dependencies. So I created my own and made it available for others. It is called ExpectIt. The advantages of my library it are stated on the project home page. You can give it a try.

以下是使用 sshj 与公共远程 SSH 服务交互的示例:

Here is an example of interacting with a public remote SSH service using sshj:

    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();
    }

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

这篇关于在 sshj 中执行命令序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 01:01
查看更多