Expect:如何在 bash 子程式中使用 Expect 腳本

Expect:如何在 bash 子程式中使用 Expect 腳本

我想在expect中寫一個登入腳本。但我希望它可以在其他不同的腳本中重複使用。我想讓所有登入命令成為 bash 子程式的一部分。即代替

expect_login.sh
#!/bin/usr/expect -f
spawn ....
set ....

我要這個:

expect_login
{
    # put some necessary command to initiate expect program

    spawn ...
    set ...
}

所以我想將此子例程放在一個文件/庫中,該文件/庫將被許多不同的腳本重用。

我怎樣才能做到這一點?

謝謝

PS:請原諒我的 bash/expect 文法不精確。我只是想以偽代碼的方式編寫。

答案1

我會選擇兩部分解決方案。一部分是expect腳本,另一部分是Shell腳本。

對於expect腳本來說,它應該是一個接受輸入並產生輸出的通用腳本。

這是我的範例期望腳本接受主機名稱和密碼,並將產生伺服器的 vcprofile 名稱

[user@server ~]$ cat getvcprofile.expect
#!/usr/bin/expect

set timeout 2

set host [lindex $argv 0]

set password [lindex $argv 1]

spawn ssh "ADMIN\@$host"

expect_after eof { exit 0 }

expect  "yes/no" { send "yes\r" }

expect  "assword" { send "$password\r" }

expect "oa>" { send "show vcmode\r" }

expect "oa>" { send "exit\r" }

exit

在 shell 腳本中,我將呼叫 Expect 腳本並為其提供變量,在本例中為 vcsystem 的主機名稱。密碼實際上是根據主機名稱 OA@XXXX 設計的模式 - 其中 XXXX 是伺服器的最後 4 位數字

[user@server ~]$ cat getvcprofile.sh
#/bin/bash

# get VC profile for a host

host=$1

#get the blade enclosure
enclosure=`callsub -enc $host |grep Enclosure: | cut -d" " -f2`

if [ ! -z $enclosure ]; then

#get the last 4 digit of the enclosure
fourdigit=${enclosure: -4}

domain=`./getvcprofile.expect ${enclosure}oa OA@${fourdigit} |grep Domain|awk '{print $NF}'`
echo $domain

else

echo "None"

fi

透過這個由兩部分組成的解決方案,我可以做這樣的事情:

for X in `cat serverlist.txt`; do echo -n $X": "; ./getvcprofile.sh $X; done 

它將列印出檔案 serverlist.txt 中每個伺服器的 vcprofile

相關內容