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:
相关推荐
月亮不月亮20 分钟前
月亮商场购物打折Java
java·eclipse
guozhetao30 分钟前
【ST表、倍增】P7167 [eJOI 2020] Fountain (Day1)
java·c++·python·算法·leetcode·深度优先·图论
技术思考者30 分钟前
基础很薄弱如何规划考研
java·经验分享·考研
●VON1 小时前
重生之我在暑假学习微服务第二天《MybatisPlus-下篇》
java·学习·微服务·架构·mybatis-plus
老华带你飞1 小时前
口腔助手|口腔挂号预约小程序|基于微信小程序的口腔门诊预约系统的设计与实现(源码+数据库+文档)
java·数据库·微信小程序·小程序·论文·毕设·口腔小程序
hqxstudying1 小时前
J2EE模式---服务层模式
java·数据库·后端·spring·oracle·java-ee
GM_8281 小时前
【最新最完整】SpringAI-1.0.0开发MCP Server,搭建MCP Client 实战笔记(进阶+详细+完整代码)
java·后端·ai编程·springai·mcp
都叫我大帅哥1 小时前
Java DelayQueue:时间管理大师的终极武器
java
秋千码途1 小时前
小架构step系列27:Hibernate提供的validator
java·spring·架构·hibernate
都叫我大帅哥1 小时前
TOGAF迁移规划阶段全解密:从菜鸟到达人的通关秘籍
java