org.apache.sshd的SshClient客户端 连接服务器执行命令 示例

引入依赖

xml 复制代码
		<dependency>
            <groupId>org.apache.sshd</groupId>
            <artifactId>sshd-core</artifactId>
            <version>2.9.1</version>
        </dependency>

示例代码,可以直接执行,也可以做替换命令、维护session等修改

java 复制代码
package com.demo.demo;

import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelExec;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.session.ClientSession;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SshdUtil {

    public static final String WHO_AM_I = "whoami";

    public static void main(String[] args) {
        execute("**.**.**.**",
                22,
                "root",
                "*****");
    }

    private static void execute(String host, int port, String username, String password) {
        SshClient client = SshClient.setUpDefaultClient();
        ClientSession session = null;
        try {
            client.start();
            ConnectFuture connectFuture = client.connect(username, host, port).verify(10, TimeUnit.SECONDS);
            if (connectFuture.isConnected()) {
                session = connectFuture.getSession();
                session.addPasswordIdentity(password);
                AuthFuture auth = session.auth().verify(10, TimeUnit.SECONDS);
                if (auth.isSuccess()) {
                    channelCmd(session, WHO_AM_I);
                }
            }
        } catch (IOException e) {
            log.error("执行异常", e);
        } finally {
            try {
                if (session != null) {
                    session.close();
                }
                client.close();
            } catch (IOException e) {
                log.error("关闭异常", e);
            }
        }
    }

    private static void channelCmd(ClientSession session, String cmd) throws IOException {
        ChannelExec channel = session.createExecChannel(cmd);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ByteArrayOutputStream outputErr = new ByteArrayOutputStream();
        channel.setOut(output);
        channel.setErr(outputErr);
        channel.open();
        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
        log.info("Output:{}", output.toString().replace("\n", "\\n"));
        log.info("Error:{}", outputErr.toString().replace("\n", "\\n"));
    }
}

输出如下,分别代表了输出流stdout和错误输出流stderr

bash 复制代码
*** [main] SshdUtil INFO  -Output:root\n
*** [main] SshdUtil INFO  -Error:
相关推荐
yinke小琪5 分钟前
凌晨2点,我删光了所有“精通多线程”的代码
java·后端·面试
迎風吹頭髮16 分钟前
UNIX下C语言编程与实践12-lint 工具使用指南:C 语言源代码语法与逻辑错误检查实战
服务器·c语言·unix
迎風吹頭髮17 分钟前
UNIX下C语言编程与实践11-UNIX 动态库显式调用:dlopen、dlsym、dlerror、dlclose 函数的使用与实例
服务器·c语言·unix
迎風吹頭髮28 分钟前
UNIX下C语言编程与实践5-C 语言编译器 cc(gcc/xlc)核心参数解析:-I、-L、-D 的使用场景与实例
服务器·c语言·unix
珹洺33 分钟前
Java-Spring入门指南(十一)代理模式与Spring AOP实战
java·spring·代理模式
JAVA学习通44 分钟前
微服务项目->在线oj系统(Java-Spring)--增删改
java·开发语言·spring
一休哥助手1 小时前
Apache Flink:流处理革命的领导者与新一代大数据计算引擎
大数据·flink·apache
SelectDB技术团队1 小时前
岚图汽车 x Apache Doris : 海量车联网数据实时分析实践
数据仓库·人工智能·数据分析·汽车·apache
道可到1 小时前
字节面试 Java 面试通关笔记 03| java 如何实现的动态加载(面试可复述版)
java·后端·面试
聪明的笨猪猪1 小时前
Spring Boot & Spring Cloud高频面试清单(含通俗理解+生活案例)
java·经验分享·笔记·面试