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

该博客介绍了如何使用Apache SSHD库建立SSH连接,并执行远程命令,例如列出文件目录结构。在过程中,提到了可能遇到的`SshException: EdDSA provider not supported`异常,解决方法是引入`eddsa`依赖。示例代码展示了从建立SSH客户端到执行命令并获取响应的完整流程。
摘要由CSDN通过智能技术生成

依赖:

<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>

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值