萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

autossh 部署指南:SSH 隧道持久化、自動重連與生產級系統服務化

SSH 隧道是運維、開發、數據同步的基礎設施,但網絡抖動、防火牆超時、服務器重啟都會導致隧道中斷。autossh 通過監控端口轉發狀態、定期發送心跳、自動重建連接,實現真正的「設置即忘記」。本文覆蓋多平台安裝、核心參數調優、Systemd 服務化、多隧道編排與故障診斷。

一、多平台安裝

系統命令備註
Debian/Ubuntusudo apt-get install autossh官方源版本通常較新
Fedorasudo dnf install autossh
CentOS/RHEL 7/8/9sudo yum install epel-release && sudo yum install autosshEPEL 必須啟用
CentOS/RHEL 7+ (源碼)見下文源碼編譯EPEL 移除了 autossh
Archsudo pacman -S autossh
Alpineapk add autossh
macOSbrew install autossh

源碼編譯通用流程(獲取最新版 1.4g+)


sudo apt-get install -y gcc make   # 或 yum install gcc make
wget https://www.harding.motd.ca/autossh/autossh-1.4g.tgz
tar xzf autossh-1.4g.tgz && cd autossh-1.4g
./configure && make && sudo make install
# 驗證
autossh -V

二、核心參數深度解析


autossh -M 0 \
  -o "ServerAliveInterval=30" \
  -o "ServerAliveCountMax=3" \
  -o "ExitOnForwardFailure=yes" \
  -o "StrictHostKeyChecking=accept-new" \
  -N -R 8080:localhost:80 user@jump-host
參數含義推薦值/說明
-M 0禁用舊式監控端口,改用 SSH 內建心跳現代 OpenSSH 5.6+ 必須設置,避免佔用額外端口
-o ServerAliveInterval=30每 30 秒發送心跳包穿透 NAT/防火牆空閒超時(通常 60-300 秒)
-o ServerAliveCountMax=3連續 3 次無響應判定斷開總容忍 ~90 秒,平衡敏感度與誤判
-o ExitOnForwardFailure=yes端口轉發建立失敗即退出觸發 autossh 重試機制,避免靜默失敗
-o StrictHostKeyChecking=accept-new首次自動接受主機鑰匙自動化部署必備,首次建議手動驗證指紋
-N不執行遠程命令,僅轉發隧道專用模式
-R 8080:localhost:80反向隧道:遠程 8080 → 本地 80內網穿透、暴露本地 Web 服務
-L 3306:db-host:3306本地隧道:本地 3306 → 遠程 db-host:3306安全訪問內網數據庫
-D 1080動態 SOCKS5 代理瀏覽器配置代理 127.0.0.1:1080

三、環境變量控制行為


export AUTOSSH_GATETIME=0          # 禁用啟動門控時間(首次連接不計入監控)
export AUTOSSH_POLL=60             # 輪詢間隔 60 秒(檢查連接狀態)
export AUTOSSH_FIRST_POLL=30       # 首次輪詢延遲 30 秒
export AUTOSSH_DEBUG=1             # 調試輸出到 stderr
export AUTOSSH_LOGLEVEL=7          # 系統日誌級別
export AUTOSSH_PATH=/usr/bin/ssh   # 指定 ssh 二進制路徑

四、Systemd 服務化(生產環境標準)

1. 單隧道服務單元 /etc/systemd/system/autossh-tunnel@.service


[Unit]
Description=AutoSSH Tunnel %i
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
Environment="AUTOSSH_GATETIME=0"
Environment="AUTOSSH_POLL=60"
ExecStart=/usr/bin/autossh -M 0 \
  -o "ServerAliveInterval=30" \
  -o "ServerAliveCountMax=3" \
  -o "ExitOnForwardFailure=yes" \
  -o "StrictHostKeyChecking=accept-new" \
  -i /etc/autossh/keys/%i.key \
  -N -R %{PORT}:localhost:%{LPORT} %{USER}@%{HOST}
Restart=always
RestartSec=10
StartLimitInterval=60
StartLimitBurst=3
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=autossh-%i

[Install]
WantedBy=multi-user.target

2. 實例化配置 /etc/autossh/tunnels.conf


# name  host        user   rport  lport  key_file
web     jump.example.com  tunnel  8080   80     web.key
db      db-proxy.internal  tunnel  3306   3306   db.key
socks   jump.example.com  tunnel  1080   1080   socks.key

3. 生成器腳本 /usr/local/bin/autossh-generator


#!/bin/bash
# 讀取 tunnels.conf 生成實例化服務
while read name host user rport lport key; do
    [[ "$name" =~ ^#.*$ ]] && continue
    cat > "/etc/systemd/system/autossh-tunnel@${name}.service" <

4. 部署與管理


# 分發私鑰(僅 tunnel 用戶可讀)
sudo mkdir -p /etc/autossh/keys
sudo cp *.key /etc/autossh/keys/
sudo chmod 600 /etc/autossh/keys/*
sudo chown root:root /etc/autossh/keys/*

# 生成並啟用服務
sudo /usr/local/bin/autossh-generator
sudo systemctl daemon-reload
sudo systemctl enable --now autossh-tunnel@web autossh-tunnel@db autossh-tunnel@socks

# 狀態查看
sudo systemctl status autossh-tunnel@web
journalctl -u autossh-tunnel@web -f

五、SSH 服務端配置協同(/etc/ssh/sshd_config)


# 允許網關端口綁定非回環地址(反向隧道對外暴露必需)
GatewayPorts yes

# 客戶端保活(配合 autossh 心跳)
ClientAliveInterval 30
ClientAliveCountMax 3

# 禁用密碼認證,強制密鑰
PasswordAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey

# 限制 tunnel 用戶僅能轉發
Match User tunnel
    ForceCommand /bin/false
    PermitTunnel no
    X11Forwarding no
    AllowTCPForwarding yes
    PermitOpen localhost:80,localhost:3306,localhost:1080

六、故障診斷清單

現象排查步驟
服務啟動即退出journalctl -u autossh-tunnel@xxx -n 50 查看錯誤;手動運行 ExecStart 命令調試
隧道建立但無流量檢查服務端 GatewayPorts yes;netstat -tlnp 確認遠程端口監聽;tcpdump -i any port 8080 抓包
頻繁重連(日誌大量重試)增加 ServerAliveInterval;檢查網絡 MTU/丟包;確認服務端 MaxSessions 未達上限
密鑰權限錯誤私鑰必須 600,父目錄 700,擁有者為運行用戶

七、替代方案對比

工具優勢劣勢適用場景
autossh輕量、標準 SSH、系統集成好單隧道單進程、無 UI服務器常駐隧道、內網穿透
ssh -o ControlMaster=auto原生多路復用、零依賴主連接斷開所有從連接失效臨時會話加速
frp/ngrokWeb 管理面板、多協議、負載均衡需部署服務端、較重大規模內網穿透、非技術用戶
systemd-socket-activate按需啟動、零常駐進程僅適用监听型服務間歇性內網服務暴露

掌握 autossh 系統化部署,讓 SSH 隧道成為基礎設施中最穩定、最無感的一環。

autossh 架構示意
copyright © 萬盛學電腦網 all rights reserved