ssh(5)端口转发autossh

什么是 autossh

autossh 是一个轻量级工具,用于增强 SSH 的可靠性。它通过监控 SSH 会话并在断开时自动重连,确保端口转发或远程连接保持可用。它的设计初衷是解决网络不稳定或服务器重启导致 SSH 连接中断的问题

核心特点

  • 自动重连:连接断开后自动尝试恢复。
  • 支持 SSH 功能:包括本地、远程和动态端口转发。
  • 后台运行:适合长时间任务。
  • 资源占用低:对系统负担小。

安装方法

在 Linux 上安装很简单:

  • Ubuntu/Debiansudo apt install autossh
  • CentOS/RHELsudo yum install autossh
  • MacOS(通过 Homebrew):brew install autossh

使用示例

  1. 本地端口转发

    1
    autossh -M 20000 -f -N -L 8080:localhost:80 [email protected]

    将本地 8080 端口转发到远程的 80 端口,-M 20000 用于监控连接。

  2. 远程端口转发

    1
    autossh -M 20000 -f -N -R 9000:localhost:3000 [email protected]

    远程服务器的 9000 端口映射到本地 3000 端口。

  3. 动态端口转发

    1
    autossh -M 20000 -f -N -D 1080 [email protected]

    创建 SOCKS5 代理,端口为 1080。

关键选项

  • -M <端口>:监控端口,检测连接状态。
  • -f:后台运行。
  • -N:仅转发,不执行命令。
  • -o:传递 SSH 选项,例如 -o "ServerAliveInterval=60" 保持连接活跃。

高级配置

  • SSH 密钥认证:避免密码输入,使用 ssh-keygen 生成密钥并配置到远程服务器。
  • 环境变量
    • AUTOSSH_POLL=60:每 60 秒检查一次连接(默认 600 秒)。
    • AUTOSSH_LOGFILE=/path/to/log:记录日志。

开机自启(以 systemd 为例)

  1. 创建服务文件:
    1
    sudo nano /etc/systemd/system/autossh-tunnel.service
  2. 输入以下内容:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    [Unit]
    Description=AutoSSH tunnel service
    After=network.target

    [Service]
    Environment="AUTOSSH_GATETIME=0"
    ExecStart=/usr/bin/autossh -M 20000 -N -L 8080:localhost:80 [email protected]
    Restart=always

    [Install]
    WantedBy=multi-user.target
  3. 启用并启动:
    1
    2
    sudo systemctl enable autossh-tunnel.service
    sudo systemctl start autossh-tunnel.service

适用场景

  • 远程访问内网服务:通过跳板机访问内网资源。
  • 持久化代理:保持 SOCKS 或 HTTP 代理可用。
  • 自动化任务:确保脚本依赖的 SSH 连接不中断。

注意事项

  • 端口冲突:检查 -M 和转发端口是否被占用。
  • 网络延迟:过高的重试频率可能增加负载。
  • 安全性:建议搭配密钥认证和防火墙规则使用。