ControlMaster 是 OpenSSH 客戶端內建功能,允許多個 SSH 會話共享同一個網路連線(Unix domain socket)。首次連線建立主連線並建立 socket 檔案,後續連線複用此 socket,無需再次驗證,大幅縮短登入時間。
本質是連線多工,非真正的 Session 複製。主連線斷開時,所有共享會話同步斷開。
Host *
ControlMaster auto
ControlPath /tmp/ssh-%r@%h:%p
ControlPersist 30m
ControlMaster auto:自動嘗試建立/使用主連線。ControlPath:Socket 檔案路徑模板。
%r:遠端登入使用者%h:遠端主機名%p:連接埠%l:本地主機名ControlPersist 30m:主連線在最後一個共享會話關閉後保持 30 分鐘(預設 0 即隨最後會話關閉)。避免頻繁重連。# 首次連線(需輸入密碼/金鑰)
ssh -v user@host
# debug 訊息會顯示:
# debug: Local connections to LOCALHOST:xxxx forwarded to remote address...
# debug: control_persist_detach: backgrounding master process
# 第二次連線(秒連)
ssh user@host
# debug 訊息:
# debug: auto-mux: Trying existing master
# debug: mux_client_request_session: master session id: 2
ls -l /tmp/ssh-*
# 輸出範例:
srw------- 1 user user 0 Oct 16 10:00 /tmp/ssh-user@host:22
ssh -O exit user@host # 關閉特定主機主連線
ssh -O stop user@host # 停止接受新多工,但保持現有會話
ssh -O check user@host # 檢查主連線狀態
生成金鑰對 → ssh-copy-id user@host → 配合 ControlMaster,首次也免密碼,後續極速。
Host bastion
HostName bastion.example.com
User admin
ControlMaster auto
ControlPath ~/.ssh/ctrl-%r@%h:%p
ControlPersist 1h
Host internal-*
HostName %h.internal.example.com
User dev
ProxyJump bastion
ControlMaster auto
ControlPath ~/.ssh/ctrl-%r@%h:%p
ControlPersist 1h
透過堡壘機存取內網主機,堡壘機與內網主機各自多工,極大提升操作流暢度。
# ansible.cfg
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=30m -o ControlPath=~/.ssh/ansible-%%r@%%h:%%p
pipelining = True
Ansible 多主機部署速度可提升 3-5 倍。
srw-------,僅擁有者可存取。ssh -S none 或 ControlMaster=no)。ssh -W (stdin/stdout forward)、某些 ProxyCommand 場景可能不相容。ControlPath 路徑需用 \\.\pipe\ssh-%r@%h:%p 格式。| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| ControlMaster | 零配置、原生支援、免重新驗證 | 主連線單點故障、不支援某些轉發 | 日常管理、腳本批次、Ansible |
| SSH 金鑰 + ssh-agent | 安全、通用、無單點故障 | 每次連線仍需完整 TCP/SSH 握手 | 所有場景基礎 |
| Mosh (Mobile Shell) | 支援漫遊、斷線重連、低延遲顯示 | 需伺服端安裝、UDP、不支援 X11 轉發 | 行動/不穩定網路 |
| tmux/screen 遠端端末多工 | 會話持久化、多視窗 | 非連線層多工、需先建立 SSH | 長時間作業、斷線恢復 |