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:
相关推荐
workflower2 小时前
单元测试-例子
java·开发语言·算法·django·个人开发·结对编程
小白银子2 小时前
零基础从头教学Linux(Day 52)
linux·运维·服务器·python·python3.11
YuanlongWang2 小时前
C# 基础——装箱和拆箱
java·开发语言·c#
b78gb2 小时前
电商秒杀系统设计 Java+MySQL实现高并发库存管理与订单处理
java·开发语言·mysql
wb043072013 小时前
性能优化实战:基于方法执行监控与AI调用链分析
java·人工智能·spring boot·语言模型·性能优化
天若有情6734 小时前
Java Swing 实战:从零打造经典黄金矿工游戏
java·后端·游戏·黄金矿工·swin
lichong9515 小时前
Android studio 修改包名
android·java·前端·ide·android studio·大前端·大前端++
lichong9515 小时前
Git 检出到HEAD 再修改提交commit 会消失解决方案
java·前端·git·python·github·大前端·大前端++
@yanyu6665 小时前
Tomcat安装与HTML响应实战
java·tomcat·html
せいしゅん青春之我5 小时前
[JavaEE初阶] 防止网络传输中的中间人入侵---证书
服务器·网络·网络协议·java-ee