Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Expect 腳本入門:讓自動化登入與批量操作變簡單

簡介:Expect 能替系統管理者完成需要互動的指令操作,例如 ssh 登入時的密碼輸入。安裝與確認路徑:

yum -y install expect   # 安裝
which expect            # /usr/bin/expect

例一:登入後保持互動

shell > cat login.exp
#!/usr/bin/expect

spawn ssh root@192.168.1.81
expect {
"(yes/no)?" { send "yes\r"; exp_continue }
"password:" { send "123456\r"; exp_continue }
"#"         { send "uptime\r"; interact }
}

要點說明:spawn 開啟一個 ssh 進程,expect 負責接收訊息,send 負責送出。首次連線遠端主機會詢問 yes/no,比對成功後送出 yes\r(\r 為換行),exp_continue 表示繼續比對下一條規則。以 root 登入成功後會拿到 # 提示符號,此時送出 uptime;interact 的意義是把控制權交還終端機,也就是登入後不退出,管理者可以繼續操作。

例二:執行完就退出

shell > cat login.exp
#!/usr/bin/expect
set timeout -1
spawn ssh root@192.168.1.81
expect {
"(yes/no)?" { send "yes\r"; exp_continue }
"password:" { send "123456\r"; exp_continue }
"#"         { send "uptime\rexit\r"; expect eof }
}

set timeout -1 把超時設為無限(也可指定秒數,如 20)。expect eof 是等待進程結束而不保持互動;若指令中沒有明確的 exit\r,就會一直等到超時才自動退出(timeout 為 -1 時則不退出)。反之,明確寫出 exit\r,命令跑完立刻登出。

例三:用 shell 迴圈批量登入

shell > cat login.sh
#!/bin/bash
list=("192.168.1.81 root 123456" "192.168.1.82 root 123456" "192.168.1.83 root 123456")
length=${#list[@]}

for ((i=0; i<$length; i++))
{
host=`echo ${list[$i]} | awk '{print $1}'`
user=`echo ${list[$i]} | awk '{print $2}'`
passwd=`echo ${list[$i]} | awk '{print $3}'`

expect -c "
spawn ssh $user@$host
expect {
\"(yes/no)?\" { send \"yes\r\"; exp_continue }
\"password:\" { send \"$passwd\r\"; exp_continue }
\"#\"         { send \"uptime\rexit\r\"; expect eof }
}
"
}

expect -c 直接從命令列執行腳本,於是就能迴圈登入各台主機、執行指令後退出。若把 exit\r 拿掉並把 expect eof 換成 interact,則會停留在遠端主機——但僅限一台,多台情況下第一台就會卡住不再往下迴圈。

例四:把參數外傳給腳本

shell > cat login.exp1
#!/usr/bin/expect
if { $argc != 3 } {
    puts "usage $argv0 user host passwd"
    exit 1
}

set user   [lindex $argv 0]
set host   [lindex $argv 1]
set passwd [lindex $argv 2]

spawn ssh $user@$host
expect {
"(yes/no)?" { send "yes\r"; exp_continue }
"password:" { send "$passwd\r"; exp_continue }
"#"         { send "uptime\r"; interact }
}

$argc 是參數個數,$argv0 是腳本名,$argv 的索引 0、1、2 依序代表第一、二、三個參數。參數不足三個時印出 usage 並結束,因此呼叫方式為 ./login.exp1 root 192.168.1.81 123456。

實務提醒:不要把明碼密碼寫進腳本檔案,改用 ssh 金鑰登入會安全得多;Expect 最合適的場景其實是那些「一定要互動」的舊式指令。

Copyright © Linux教程網 All Rights Reserved