expect是用來實現自動交互功能的工具之一,使用expect-send來實現交互過程。
注意:
1、腳本的執行方法與bash shell不一樣,比如:expect example.sh
2、向一個腳本傳遞參數時,bash shell是使用$1,$2...來接收參數的;而expect則將腳本的執行參數保存在數組$argv中,在腳本中一般將其賦值給變量:set 變量名 [lindex $argv 參數]
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/usr/bin/expect
set
ip [lindex $argv 0]
set
password [lindex $argv 1]
set
timeout 2
spawn telnet $ip
expect
"*femto login:"
send
"root\r"
expect
"*Password:"
send
"$password\r"
# 進入指定的機器后,就可執行相應的命令或者腳本
interact
#expect eof
|
注意:若登陸后便退出遠程終端,則寫expect eof
即可。
3、執行腳本
1
|
expect autologin.sh 192.168.1.240 root
|
很多時候,需要用expect命令實現登錄遠端服務器執行簡單命令,諸如:重啟服務器,ftp,ls, scp等命令。 里面涉及到輸入密碼的交互式場景,這個時候expect命令的巨大功效就出來了,下面是一個比較經典腳本實現:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#!/usr/bin/tclsh
package require Expect
set
host_ip1 [lindex $argv 0]
set
host_usr [lindex $argv 1]
set
host_pwd [lindex $argv 2]
spawn
ssh
$host_usr@$host_ip1
set
timeout 60
expect {
-re
"password"
{send
"$host_pwd\n"
}
-re
"yes/no"
{send
"yes\n"
;exp_continue}
# 有的時候輸入幾次密碼來確認,exp_continue
}
expect
"#"
send
"ls /home/${host_user} | tee -a /tmp/ls.txt \r"
expect
"#"
send
"exit\r"
expect eof
|
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接