公网反向 SSH 隧道:用 Hermes Agent 操控内网 Ubuntu

背景

家里的 Ubuntu 没有公网 IP,但又想通过飞书上的 Hermes Agent 来操控它。直接暴露 SSH 端口到公网不安全,反向 SSH 隧道是最优雅的解法。

原理: Ubuntu 主动向外连接到 Oracle 服务器,建立一个反向隧道。Oracle 上的 Hermes 连接本地端口,实际通信通过隧道回到 Ubuntu。

前置条件

  • 一台有公网 IP 的服务器(本文以 Oracle Cloud 为例,IP 150.230.5.211
  • 一台内网的 Ubuntu 机器
  • Ubuntu 上已安装 OpenSSH Server(sudo apt install openssh-server

第一步:Oracle 上生成 SSH Key

ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -N "" -C "hermes-oracle"

查看公钥内容:

cat ~/.ssh/id_ed25519.pub

会得到类似这样的输出:

ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICkgb19znwNDI1ys9mjdx1GYXiRoTEfZtiVA3ELhNbpx hermes-oracle

第二步:Ubuntu 上添加公钥

在 Ubuntu 上,将上一步得到的公钥追加到 authorized_keys

echo 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICkgb19znwNDI1ys9mjdx1GYXiRoTEfZtiVA3ELhNbpx hermes-oracle' >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

第三步:Ubuntu 上安装 autossh

autossh 会在 SSH 连接断开时自动重连,保证隧道持久在线:

sudo apt install autossh -y

第四步:Ubuntu 上创建 systemd 服务(开机自启)

创建服务文件:

sudo tee /etc/systemd/system/hermes-tunnel.service << 'EOF'
[Unit]
Description=Hermes Reverse SSH Tunnel to Oracle
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=derek
ExecStart=/usr/bin/autossh -M 0 \
  -o "ServerAliveInterval=30" \
  -o "ServerAliveCountMax=3" \
  -o "ExitOnForwardFailure=yes" \
  -N -R 13389:localhost:22 root@150.230.5.211
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

⚠️ 把 你的Ubuntu用户名 替换成实际的用户名,比如 ubuntuderek 等。

启动并设为开机自启:

sudo systemctl daemon-reload
sudo systemctl enable --now hermes-tunnel.service

检查状态:

sudo systemctl status hermes-tunnel.service

第五步:Oracle 上创建 Hermes Profile

回到 Oracle 服务器,创建一个专门用于操控 Ubuntu 的 profile:

hermes profile create ubuntu

配置 SSH 后端,指向本地 13389 端口(即反向隧道的入口):

hermes --profile ubuntu config set terminal.backend ssh
hermes --profile ubuntu config set terminal.ssh.host 127.0.0.1
hermes --profile ubuntu config set terminal.ssh.port 13389
hermes --profile ubuntu config set terminal.ssh.user 你的Ubuntu用户名
hermes --profile ubuntu config set terminal.ssh.key_path /root/.ssh/id_ed25519

验证配置:

cat /root/.hermes/profiles/ubuntu/config.yaml

应该输出:

terminal:
  backend: ssh
  ssh:
    host: 127.0.0.1
    port: 13389
    user: 你的Ubuntu用户名
    key_path: /root/.ssh/id_ed25519

第六步:验证隧道连通性

在 Oracle 上确认 13389 端口已在监听:

ss -tlnp | grep 13389

如果能看到监听,说明隧道已建立。

测试 SSH 连接:

ssh -i ~/.ssh/id_ed25519 -p 13389 你的Ubuntu用户名@127.0.0.1

如果能成功登录 Ubuntu,说明一切正常。


如何使用

CLI 模式

在 Oracle 命令行直接使用 ubuntu profile:

# 启动交互式会话,所有终端命令在 Ubuntu 上执行
hermes --profile ubuntu

# 一句指令
hermes --profile ubuntu chat -q "查看 Ubuntu 的内存使用情况"

飞书/Telegram 模式

如果正在通过飞书与 Oracle Hermes 对话,可以直接切 profile:

/profile ubuntu

之后的所有终端命令都会在 Ubuntu 上执行。切回 Oracle 用:

/profile default

总结

这套方案的优势:

特性 说明
零端口暴露 Ubuntu 不需要对外开放任何端口
自动重连 autossh + systemd 保证隧道断线秒级恢复
多机切换 通过 profile 在 Oracle 和 Ubuntu 之间自由切换
飞书统一入口 不用管多个机器人,一个飞书对话控制两台机器

如果你需要在不同内网机器之间切换,重复第二步到第四步,每台机器建一个不同的 profile 即可。