Autossh 是一款監控 SSH 連線並在中斷時自動重連的工具,適合建立長期穩定的 SSH 隧道、反向代理、資料庫轉發等場景。本文整理各主流 Linux 發行版的安裝方式,包含套件管理器安裝與原始碼編譯。

| 發行版 | 安裝指令 |
|---|---|
| Debian/Ubuntu | sudo apt-get install autossh |
| Fedora | sudo dnf install autossh (或 yum) |
| CentOS/RHEL 6/7 | 需啟用 EPEL:sudo yum install epel-release && sudo yum install autossh |
| CentOS/RHEL 8+ | EPEL 中已移除 autossh,建議原始碼編譯 |
| Arch Linux | sudo pacman -S autossh |
sudo apt-get install gcc make
wget https://www.harding.motd.ca/autossh/autossh-1.4e.tgz
tar -xf autossh-1.4e.tgz
cd autossh-1.4e
./configure
make
sudo make install
sudo yum install wget gcc make
後續編譯步驟相同。
autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" \
-NR 8080:localhost:80 user@remote-server
-M 0:停用監控埠,改用 SSH 內建 KeepAlive。ServerAliveInterval 30:每 30 秒發送心跳。ServerAliveCountMax 3:3 次無回應視為斷線。-NR:反向隧道(遠端 8080 → 本地 80),不佔用本地終端機。建立 /etc/systemd/system/autossh-tunnel.service:
[Unit]
Description=AutoSSH Tunnel
After=network.target
[Service]
User=youruser
Environment="AUTOSSH_GATETIME=0"
ExecStart=/usr/local/bin/autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -NR 8080:localhost:80 user@remote-server
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
啟用:sudo systemctl daemon-reload && sudo systemctl enable --now autossh-tunnel
AUTOSSH_GATETIME=0:關閉閘門時間,立即重連。AUTOSSH_POLL=60:檢查間隔(秒)。AUTOSSH_FIRST_POLL=30:首次檢查延遲。AUTOSSH_DEBUG=1:除錯模式。Autossh 讓 SSH 隧道具備生產級可靠性,是遠端維運、跨雲端網路互通的關鍵工具。