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:
相关推荐
captain3764 小时前
MyBatis(入门5)其他查询操作
java·数据库·spring boot·mybatis
Novproxy_Z4 小时前
商用代理避坑:如何识别商家拿机房 IP 冒充住宅 IP
java·网络·tcp/ip
无足鸟ICT4 小时前
【RHCA+】vmstat命令(监控系统资源)
linux·服务器
垆边人似月.4 小时前
RDMA 文件传输踩坑(五):READY 发送成功后,为什么出现 Work Request Flushed Error?
服务器·网络·tcp/ip
闪亮的路灯4 小时前
Linux 安装mqtt服务mosquitto
linux·运维·服务器
HideF5 小时前
nmcli
linux·服务器·网络
文丑颜不良啊5 小时前
LeetCode1481~1500题目解析
java·leetcode
2601_962885725 小时前
quotes 字段全解:涨跌幅、振幅、换手率的口径与单位
java·前端·spring
前端精髓5 小时前
调用openrouter的免费API模型
java·前端·javascript
qetfw5 小时前
UOS DHCP Relay:跨网段分配与 IP、DNS、网关验证
linux·服务器·网络·tcp/ip·uos