Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 安裝 Autossh 實現 SSH 連線自動重連與隧道持久化完整指南

編輯:關於 Linux

Autossh 是一套監控 SSH 連線狀態、自動重連、維持反向/正向隧道存活的工具。適用於不穩定網路環境、跳板機隧道、內網穿透、遠端日誌收集等場景。本文涵蓋主流發行版安裝方式、原始碼編譯、systemd 服務化部署與核心參數調優。

Autossh 架構示意圖

各發行版預編譯套件安裝

發行版安裝指令備註
Debian / Ubuntu sudo apt-get install autossh 官方倉庫內建
Fedora sudo dnf install autossh 官方倉庫內建
CentOS / RHEL 6/7 sudo yum install autossh 需啟用 EPEL / Repoforge
CentOS / RHEL 8/9 無預編譯套件 需原始碼編譯 (見下)
Arch Linux sudo pacman -S autossh 官方倉庫內建

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

# 安裝建置工具
# Debian/Ubuntu
sudo apt-get install gcc make
# CentOS/RHEL
sudo yum install gcc make

# 下載原始碼 (官網最新版 1.4g)
wget https://www.harding.motd.ca/autossh/autossh-1.4g.tgz
tar -xf autossh-1.4g.tgz
cd autossh-1.4g

# 編譯安裝
./configure
make
sudo make install
# 預設安裝至 /usr/local/bin/autossh

核心參數詳解

參數說明建議值
-M 監控埠 (雙向 echo 服務),0 表示關閉,改用 SSH 內建 ServerAliveInterval -M 0
-f 背景執行 (fork to background) 生產環境必加
-N 不執行遠端指令,僅建立隧道 隧道模式必加
-o "ServerAliveInterval=30" 每 30 秒發送保活封包 防火牆/NAT 斷開偵測
-o "ServerAliveCountMax=3" 3 次無回應視為斷線 觸發 autossh 重連
-o "ExitOnForwardFailure=yes" 端口轉發失敗即退出 避免靜默失敗
-R :: 反向隧道 (遠端→本地) 內網穿透核心參數
-L :: 正向隧道 (本地→遠端) 跳板機存取內網服務

實戰部署範例:systemd 服務化 (開機自啟、自動重啟)

建立服務檔

sudo vim /etc/systemd/system/autossh-tunnel.service
[Unit]
Description=AutoSSH Reverse Tunnel to Jump Host
After=network.target

[Service]
User=autossh
Environment="AUTOSSH_GATETIME=0"
Environment="AUTOSSH_POLL=60"
Environment="AUTOSSH_FIRST_POLL=30"
Environment="AUTOSSH_LOGLEVEL=7"
Environment="AUTOSSH_LOGFILE=/var/log/autossh.log"
ExecStart=/usr/local/bin/autossh -M 0 -f -N \
    -o "ServerAliveInterval=30" \
    -o "ServerAliveCountMax=3" \
    -o "ExitOnForwardFailure=yes" \
    -o "StrictHostKeyChecking=no" \
    -o "UserKnownHostsFile=/dev/null" \
    -i /home/autossh/.ssh/id_rsa \
    -R 2222:localhost:22 \
    autossh@jump-host.example.com
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

啟用服務

sudo systemctl daemon-reload
sudo systemctl enable autossh-tunnel
sudo systemctl start autossh-tunnel
sudo systemctl status autossh-tunnel
journalctl -u autossh-tunnel -f

環境變數微調 (依環境調整)

  • AUTOSSH_GATETIME=0:關閉啟動門檻檢查 (避免首次連線慢被誤判)
  • AUTOSSH_POLL=60:輪詢間隔 60 秒
  • AUTOSSH_LOGLEVEL=7:詳細除錯日誌
  • AUTOSSH_PATH:指定 ssh 執行檔路徑 (非標準位置時)

進階:多隧道管理策略

  • 每組隧道建立獨立 systemd 服務 (autossh-tunnel-)
  • 使用 systemd 模板單元 (autossh-tunnel@.service) 參數化管理
  • 搭配 monit 或 Prometheus node_exporter 監控連線狀態

Autossh + systemd 讓 SSH 隧道具備生產級的高可用性,是維運自動化、混合雲互聯、內網服務暴露的基石工具。

Copyright © Windows教程網 All Rights Reserved