java连接远程服务器--SSHD方式

依赖:

<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-core</artifactId>
    <version>2.8.0</version>
</dependency>

demo

 public static void main(String[] args) throws IOException {
            System.out.println(new Date().toString());
            listFolderStructure("root", "password", "ip", 22, 5, "ls");
            System.out.println(new Date().toString());
        }
    }

    public static void listFolderStructure(String username, String password,

                                       String host, int port, long defaultTimeoutSeconds, String command) throws IOException {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();
        try (ClientSession session = client.connect(username, host, port)
                .verify(defaultTimeoutSeconds, TimeUnit.SECONDS).getSession()) {
            session.addPasswordIdentity(password);
            session.auth().verify(defaultTimeoutSeconds, TimeUnit.SECONDS);
            try (ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
                 ClientChannel channel = session.createExecChannel(command)) {
                channel.setOut(responseStream);
                try {
                   channel.open().verify(defaultTimeoutSeconds, TimeUnit.SECONDS);

                    try (OutputStream pipedIn = channel.getInvertedIn()) {
                        pipedIn.write(command.getBytes());
                        pipedIn.flush();
                    }

                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED),          TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds));
                    String responseString = new String(responseStream.toByteArray());
                    System.out.println(responseString);
                } finally {
                    channel.close(false);
                }

            }
        } finally {
            client.stop();
        }
    }

结果
在这里插入图片描述

备注
1.如下图所示: 有三种类型的channel可选;


<**
   String CHANNEL_EXEC = "exec";
    String CHANNEL_SHELL = "shell";
    String CHANNEL_SUBSYSTEM = "subsystem";
*>
ClientChannel channel = session.createExecChannel(command)) 

在这里插入图片描述
2.图一中的 (SshException) to process: EdDSA provider not supported异常:
添加依赖eddsa可解决。

<dependency>
    <groupId>net.i2p.crypto</groupId>
    <artifactId>eddsa</artifactId>
    <version>0.3.0</version>
</dependency>