autossh介绍

什么是 Autossh?

autossh 是一个增强版的 SSH 工具,用于自动监控和重启 SSH 隧道。如果网络不稳定或连接断开,autossh 会尝试重新建立连接,非常适合需要持久隧道的场景,比如你的 Open WebUI 和 Ollama 服务。


前置条件

  1. 安装 Autossh

    • macOS:brew install autossh(需先安装 Homebrew)。
    • Ubuntu/Debian:sudo apt-get install autossh
    • CentOS/RHEL:sudo yum install autossh
  2. SSH 密钥认证

    • autossh 需要无密码登录,因为它无法交互输入密码。
    • 在旧电脑上生成密钥对:
      1
      ssh-keygen -t rsa -b 4096
      回车接受默认路径(~/.ssh/id_rsa),无需设置密码。
    • 将公钥添加到云服务器:
      1
      ssh-copy-id root@yukun.xin
  3. 测试普通 SSH

    • 先用普通 ssh 测试,确保连接正常。例如:
      1
      ssh -R 0.0.0.0:3000:localhost:3000 root@yukun.xin

使用 Autossh 的步骤

1. 基本用法

autossh 的命令与 ssh 类似,只需将 ssh 替换为 autossh,并添加一些参数。

  • 示例(单端口反向转发):
    1
    autossh -M 0 -f -N -R 0.0.0.0:3000:localhost:3000 root@yukun.xin
    • -M 0:禁用监控端口(推荐使用 ServerAlive 替代,见下文)。
    • -f:后台运行。
    • -N:不执行远程命令,仅转发端口。
    • -R 0.0.0.0:3000:localhost:3000:反向转发,将云服务器的 3000 端口映射到旧电脑的 localhost:3000

2. 多端口转发

你需要同时映射 Open WebUI(3000)和 Ollama(11434)。命令如下:

1
autossh -M 0 -f -N -R 0.0.0.0:3000:localhost:3000 -R 0.0.0.0:11434:localhost:11434 root@yukun.xin
  • 这会将云服务器的 300011434 端口分别映射到旧电脑的对应端口。

3. 增强稳定性

添加 ServerAlive 参数,确保检测连接状态并自动重连:

1
autossh -M 0 -f -N -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -R 0.0.0.0:3000:localhost:3000 -R 0.0.0.0:11434:localhost:11434 root@yukun.xin
  • ServerAliveInterval 30:每 30 秒发送一次保活信号。
  • ServerAliveCountMax 3:连续 3 次未收到响应则认为连接断开,触发重连。