Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

expect 在 Linux 下的實戰應用

用 ssh 或 scp 時總要手打密碼,這在批次管理幾十台主機時完全不可行。expect 這支工具能自動處理互動式提示,是自動化維運的常備武器。

先看最小範例

#!/usr/bin/expect
set timeout 30
spawn ssh -l root 192.168.1.188
expect "password:"
send "abc123456\r"
interact

逐行說明:

第 1 行宣告用哪個 shell 執行,必須在第一行。expect 與 bash、cmd 同屬 shell 層級的東西。

第 2 行設定超時秒數。

第 3 行的 spawn 是 expect 的內部指令,只有進入 expect 環境後才存在,所以別用 which spawn 去找它,就像 Windows 的 dir 是 shell 內建一樣。它的作用是給 ssh 進程套一個殼,用來傳遞互動指令。

第 4 行的 expect 也是內部指令,作用是判斷上次輸出裡是否含「password:」,有就立刻返回,沒有就等到 30 秒超時。

第 5 行 send 執行互動動作,等同手動輸入密碼。字串結尾別忘了 \r,出現異常等待時優先檢查這裡。

第 6 行 interact 把控制權交回終端,讓你可以繼續手動操作。少了這行,登入後會直接退出。

案例一:遠端執行指令

#!/usr/bin/expect -f
set timeout 30
spawn ssh -l root 192.168.1.188
expect {
  "yes/no" { send "yes\r";exp_continue }
  "password:" { send "abc123456\r" }
}
expect -re "\](\$|#) "
send "bash /root/test.sh \r"
expect -re "\](\$|#) "
send "exit\r"

-re 表示用正則匹配,這裡用來等待 shell 提示符。也可以改寫成一行 invoke 的形式:

#!/bin/bash
expect -c "
spawn ssh root@192.168.1.188 \"ifconfig;whoami;pwd;echo hello;\"
expect {
 \"*assword\" {set timeout 30; send \"abc123456\r\";}
 \"yes/no\" {send \"yes\r\"; exp_continue;}
}
expect eof
"

-c 表示直接在命令列執行 expect。注意這種寫法過程中不會有 shell 提示符。

案例二:批次處理多台主機

先把主機清單寫成 host.list,每行「IP 連接埠 使用者 密碼」:

192.168.1.1 22 root abc1
192.168.1.2 22 root abc2
192.168.1.3 22 root abc3

主腳本 main.exp 用 argv 取參數:

#!/usr/bin/expect -f
set ipaddress [lindex $argv 0]
set port [lindex $argv 1]
set username [lindex $argv 2]
set passwd [lindex $argv 3]
set timeout 30
spawn ssh $ipaddress -p$port -l$username
expect { "yes/no" { send "yes\r";exp_continue } "password:" { send "$passwd\r" } }
expect -re "\](\$|#) "
send "bash /root/test.sh \r"
expect -re "\](\$|#) "
send "exit\r"

外層用 while 迴圈喂資料:

#!/bin/bash
host="host.list"
while read line
do
  expect main.exp $line
done < $host

兩個腳本都給執行權限即可。

案例三:scp 傳輸

expect -c "
spawn scp root@192.168.1.188:/root/file1.tgz /root
expect {
 \"*assword\" {set timeout 300; send \"abc123456\r\";}
 \"yes/no\" {send \"yes\r\"; exp_continue;}
}
expect eof
"

大檔案記得把 timeout 調長,否則會在中途被切斷。

更安全的替代思路

把明文密碼寫進腳本,本身就是個風險點:檔案權限、版本控制外洩、主機清單外流都會連帶出事。生產環境更推薦兩種做法:一是在主機之間建立 SSH 金鑰信任機制,直接免密登入;二是使用 sshpass 這類專門工具,並搭配權限收斂與密碼集中管理。expect 的定位,更适合一次性、臨時性的批次操作。

Copyright © Linux教程網 All Rights Reserved