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 {
        }
    }
}
相关推荐
Web3探索者16 小时前
可视化服务器管理和传统命令行区别是什么?新手教程:Linux 运维到底该用图形界面还是 SSH 命令行?
linux·ssh
荣--20 小时前
一键部署不是为了省时间 —— 它是把"买来的 PaaS"变成"自己的平台"的拐点
运维·zabbix·工程化·一键部署·平台化·边界设计
江华森20 小时前
动手实战学 Docker — 从零到集群编排完全指南
运维
Avan_菜菜2 天前
FRP 内网穿透完整实战:从 HTTP 映射到 HTTPS 自签代理
运维·nginx·https
SelectDB3 天前
Litefuse 开源并推出单进程轻量模式,25 秒就能跑起来的 Agent 可观测与评估平台
运维·后端·自动化运维
zzzzzz3104 天前
9K Star 炸裂开源!这个 C 语言写的代码知识图谱,把 Linux 内核索引压缩到了 3 分钟
linux·服务器·sql
XIAOHEZIcode4 天前
Linux系统鼠标偏移常见原因以及修复方案
linux·运维·游戏
用户0328472220705 天前
如何搭建本地yum源(上)
运维
大树888 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠8 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql