expect腳本登錄
Ⅰ 如何用expect寫一個自動登錄腳本
1.安裝expect
需要先安裝tcl:apt-get install tcl
apt-get install expect
2.expect使用
2.1一個簡單的輸入密碼操作
#!/usr/bin/expect
set timeout 100
set password "123456"
spawn sudo rm -rf zzlogic
expect "root123456"
send "$password "
interact
說明:
第一行#!/usr/bin/expect表示使用expect的shell交互模式
set是對變數password賦值
set timeout 100:設置超時時間為100秒,如果要執行的shell命令很長可以設置超時時間長一些。expect超過超時時間沒有監測到要找的字元串,則不執行,默認timeout為10秒
spawn在expect下執行shell腳本
expect對通過spawn執行的shell腳本的返回進行判斷,是否包含「」中的欄位
send:如果expect監測到了包含的字元串,將輸入send中的內容, 相當於回車
interact:退出expect返回終端,可以繼續輸入,否則將一直在expect不能退出到終端
2.2expect的命令行參數
[lindex $argv n]獲得index為n的參數(index從0開始計算)
$argc為命令行參數的個數
[lrange $argv 0 0]表示第一個參數
[lrange $argv 0 3]表示第1到第3個參數
例如scp_service.sh文件,可以./scp_service.sh -rm來執行,這時是賦值了一個參數
set option [lindex $argv 0](獲得第一個參數存到變數option中,參數是的index是從0開始計算的)
2.3if...elif...else...
expect支持if語句,
if {條件1} {
條件1執行語句
} elif {條件2} {
條件2執行語句
} else {
其他情況執行語句
}
說明:
1.if的條件用{}來包含條件
2.if和後面的{}必須有空格隔開
3.兩個花括弧之間必須有空格隔開,比如if {} {},否則會報錯 expect:extra characters after close-brace
3.使用{來銜接下一行,所以if的條件後需要加左花括弧{
4.else不能單獨放一行,所以else要跟在}後面
2.4 expect {},多行期望,匹配到哪條執行哪條
背景:有時執行shell後預期結果是不固定的,有可能是詢問是yes/no,有可能是去輸入密碼,所以可以用expect{}
花括弧內放多行語句,從上至下匹配,匹配到哪個expect執行哪句。
3.shell中調用expect來實現登錄
我是通過在shell腳本中執行expect腳本的方式來實現的。當然可以將shell中定義的一些變數傳遞給expect腳本作為參數輸入。
Ⅱ linux下expect腳本問題
#!/usr/bin/expect-f
if{$argc!=1}{
puts"usage:$argv0IP"
exit1
}else{
setIP[lindex$argv0]
}
setpingcmd[format"ping-c100%s"$IP]
settimeout6000
#比如遠程用戶叫做test
setdestusertest
#比如遠程伺服器IP為如下
setdestip192.168.0.123
setdestpath"$destuser@$destip"
#比如用戶密碼叫做test
setdestpasswordtest
#ssh登錄
spawnssh$destpath
#######################
expect{
-re".*yes/no.*"{
exp_send"yes "
exp_continue
}
-re".*assword.*"{
exp_send"$destpassword "
}
}
#比如ssh登錄以後的提示符是test@Testserver>
expect{
-re".*test@Testserver.*"{
exp_send"$pingcmd "
}
}
expect{
#如果輸出timeout字元,則Control+C結束pingcmd
#這里用的是DestinationHostUnreachabl替換timeout。因為本人機器上沒有timeout.
-re".*DestinationHostUnreachabl.*"{
#輸入Control+c
exp_send"