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:
相关推荐
he25819几秒前
centOS 7.9 安装JDK MYSQL
java·mysql·centos
找了一圈尾巴12 分钟前
Spring Boot 日志管理(官网文档解读)
java·spring boot
升讯威在线客服系统12 分钟前
如何通过 Docker 在没有域名的情况下快速上线客服系统
java·运维·前端·python·docker·容器·.net
s:1031 小时前
【框架】参考 Spring Security 安全框架设计出,轻量化高可扩展的身份认证与授权架构
java·开发语言
南山十一少4 小时前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
勤奋的凯尔森同学5 小时前
webmin配置终端显示样式,模仿UbuntuDesktop终端
linux·运维·服务器·ubuntu·webmin
427724006 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
丁卯4046 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
chengooooooo6 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
李长渊哦6 小时前
常用的 JVM 参数:配置与优化指南
java·jvm