需要同時 SSH 登入多台伺服器,且希望在同一個 GNOME Terminal 視窗的不同標籤頁中完成。手動開啟標籤再輸入指令太繁瑣,結合 gnome-terminal --tab 與 expect 可實現全自動化。
核心指令結構
gnome-terminal \
--tab --title="Server-1" -- bash -c "expect -c 'spawn ssh user@192.168.1.10; expect \"password:\"; send \"mypwd\r\"; interact'" \
--tab --title="Server-2" -- bash -c "expect -c 'spawn ssh user@192.168.1.11; expect \"password:\"; send \"mypwd\r\"; interact'" \
--tab --title="Server-3" -- bash -c "expect -c 'spawn ssh user@192.168.1.12; expect \"password:\"; send \"mypwd\r\"; interact'"
參數詳解
| 參數 | 作用 |
--tab | 新增一個標籤頁 |
--title="名稱" | 設定標籤標題,方便識別 |
-- bash -c "..." | 在標籤中啟動 bash 並執行引號內指令 |
expect -c '...' | 直接執行 expect 腳本片段,無需外部檔案 |
spawn ssh ... | 啟動 ssh 連線 |
expect \"password:\" | 等待密碼提示 |
send \"mypwd\r\" | 發送密碼並換行 |
interact | 將控制權交還使用者,保持互動模式 |
進階:將伺服器清單外置為陣列
#!/bin/bash
servers=(
"web01|192.168.10.11|pass123"
"db01|192.168.10.21|pass456"
"cache01|192.168.10.31|pass789"
)
cmd="gnome-terminal"
for s in "${servers[@]}"; do
IFS='|' read -r name ip pwd <<< "$s"
cmd+=" --tab --title=\"$name\" -- bash -c \"expect -c 'spawn ssh user@$ip; expect \"password:\"; send \"$pwd\r\"; interact'\""
done
eval "$cmd"
安全性建議
- 生產環境禁止在腳本明文寫密碼
- 改用
ssh-keygen -t ed25519 產生金鑰對,ssh-copy-id user@host 部署公鑰
- 腳本改為
spawn ssh -i ~/.ssh/id_ed25519 user@host,免密登入
- 若必須用密碼,可搭配
sshpass -p 'pwd' ssh ...(需安裝 sshpass)
常見問題排查