萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 安裝 Autossh 實現 SSH 連線自動重連與穩定隧道

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

套件管理器快速安裝

發行版安裝指令
Debian/Ubuntusudo apt-get install autossh
Fedorasudo dnf install autossh (或 yum)
CentOS/RHEL 6/7需啟用 EPEL:sudo yum install epel-release && sudo yum install autossh
CentOS/RHEL 8+EPEL 中已移除 autossh,建議原始碼編譯
Arch Linuxsudo pacman -S autossh

原始碼編譯安裝(通用,可獲最新版)

Debian/Ubuntu 環境準備

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

CentOS/RHEL/Fedora 環境準備

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),不佔用本地終端機。

系統服務化(systemd)

建立 /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 隧道具備生產級可靠性,是遠端維運、跨雲端網路互通的關鍵工具。

copyright © 萬盛學電腦網 all rights reserved