Java ApacheSSHD实现SSH代理

SSH 协议代理 为核心,对外提供标准 SSH 服务入口,对内作为 Linux 服务器集群的统一跳板网关。通过双向流转发技术,实现用户终端与目标 Linux 系统的透明交互,同时集成认证、鉴权、会话审计等安全能力,为企业提供 "安全、可控、可审计" 的 Linux 远程运维解决方案。

效果图

流程图

外层还是通过Xshell连接,堡垒机对SSH数据流进行了转发。

代码详细

POM添加

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

<!-- 工具包 -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.25</version>
</dependency>

代码 JavaSshServer

java 复制代码
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.server.*;
import org.apache.sshd.server.auth.AsyncAuthException;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.channel.ChannelSession;
import org.apache.sshd.server.command.Command;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.session.ServerSession;
import org.apache.sshd.server.shell.ShellFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class JavaSshServer {
    private static final String LINUX_HOST = "127.0.0.1";
    private static final int LINUX_PORT = 2222;
    private static final String LINUX_USER = "root";
    private static final String LINUX_PWD = "123456";

    public static void main(String[] args) {
        try {
            // 1. 创建 SSH 服务
            SshServer sshd = SshServer.setUpDefaultServer();
            sshd.setPort(8888);

            sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());

            sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
                @Override
                public boolean authenticate(String username, String password, ServerSession serverSession) throws PasswordChangeRequiredException, AsyncAuthException {
                    // 判断逻辑
                   return  "admin".equals(username) && "123456".equals(password);
                }
            });

            sshd.setShellFactory(new ShellFactory() {
                @Override
                public Command createShell(ChannelSession channelSession) {
                    return new LinuxShellCommand(); // 返回自定义 Command
                }
            });

            // ===================== 启动
            sshd.start();

            System.out.println("==================================");
            System.out.println("✅ SSH 服务启动成功");
            System.out.println("✅ 地址:localhost:8888");
            System.out.println("✅ 账号:admin  密码:123456");
            System.out.println("==================================");

            Thread.sleep(1000 * 200000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static class LinuxShellCommand implements Command {
        private InputStream in;
        private OutputStream out;
        private OutputStream err;
        private ExitCallback callback;

        @Override
        public void setInputStream(InputStream in) {
            this.in = in;
        }

        @Override
        public void setOutputStream(OutputStream out) {
            this.out = out;
        }

        @Override
        public void setErrorStream(OutputStream err) {
            this.err = err;
        }

        @Override
        public void setExitCallback(ExitCallback callback) {
            this.callback = callback;
        }

        @Override
        public void start(ChannelSession channelSession, Environment env) throws IOException {
            // 1. 连接 Linux
            SshClient client = SshClient.setUpDefaultClient();
            client.start();

            ClientSession session = client.connect(LINUX_USER, LINUX_HOST, LINUX_PORT)
                    .verify(60000).getSession();
            session.addPasswordIdentity(LINUX_PWD);
            session.auth().verify(60000);

            // 2. 打开 Linux Shell
            ChannelShell channel = session.createShellChannel();
            channel.open().verify(60000);

            // 3. 流对接:Xshell ↔ Linux
            transfer(in, channel.getInvertedIn());    // 输入
            transfer(channel.getInvertedOut(), out);   // 输出
            transfer(channel.getInvertedErr(), err);   // 错误
        }

        // 流转发
        private void transfer(InputStream from, OutputStream to) {
            new Thread(() -> {
                try {
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = from.read(buf)) != -1) {
                        to.write(buf, 0, len);
                        to.flush();
                    }
                } catch (Exception ignored) {
                }
            }).start();
        }

        @Override
        public void destroy(ChannelSession channelSession) throws Exception {
        }
    }
}
相关推荐
杨云龙UP3 小时前
MySQL 数据库常用备份工具对比:mysqldump、mydumper 与 XtraBackup
linux·运维·服务器·数据库·mysql·dba·备份恢复
PC2005-cloud3 小时前
从零上手 openGauss:Docker 部署 + 全场景连接教程
运维·docker·容器
独隅4 小时前
Cursor+GitOps 自动化运维实战:智能编写 Ansible 与 Terraform
运维·自动化·ansible
happymagic4 小时前
java spring boot做的jar包程序,如何实现自动运行启动
java·运维·服务器·spring boot·jar
星空你好4 小时前
AI辅助运维:开源一个内网日志监控工具
运维
风曦Kisaki5 小时前
Kubernetes(K8s)笔记Day06: 持久化存储(emptyDir,hostPath,NFS),PV 和 PVC,StorageClass存储类
linux·运维·笔记·云原生·容器·kubernetes
Dr.kangder5 小时前
嵌入式处理器仿真技术——Hypervisor 原理与实践
服务器·嵌入式硬件·架构·嵌入式
星蓝_starblue7 小时前
零服务器、零数据库!开源growth-board,利用GitHub自动管理刷题/学习/求职全流程
服务器·数据库·程序人生·系统架构·node.js·github·改行学it
回眸&啤酒鸭8 小时前
【回眸】搞钱灵感——自动化敏捷开发项目管理系统落地设计
运维·自动化·敏捷流程
Crazy________9 小时前
k8s部署若依微服务架构流程,v3.6.6
运维·云原生·容器·kubernetes·状态模式