expect是用來實(shí)現(xiàn)自動(dòng)交互功能的工具之一,使用expect-send來實(shí)現(xiàn)交互過程。
注意:
1、腳本的執(zhí)行方法與bash shell不一樣,比如:expect example.sh
2、向一個(gè)腳本傳遞參數(shù)時(shí),bash shell是使用$1,$2...來接收參數(shù)的;而expect則將腳本的執(zhí)行參數(shù)保存在數(shù)組$argv中,在腳本中一般將其賦值給變量:set 變量名 [lindex $argv 參數(shù)]
#!/usr/bin/expectset ip [lindex $argv 0]set password [lindex $argv 1]set timeout 2spawn telnet $ipexpect "*femto login:"send "root/r"expect "*Password:"send "$password/r"# 進(jìn)入指定的機(jī)器后,就可執(zhí)行相應(yīng)的命令或者腳本interact#expect eof
注意:若登陸后便退出遠(yuǎn)程終端,則寫expect eof即可。
3、執(zhí)行腳本
expect autologin.sh 192.168.1.240 root
很多時(shí)候,需要用expect命令實(shí)現(xiàn)登錄遠(yuǎn)端服務(wù)器執(zhí)行簡單命令,諸如:重啟服務(wù)器,ftp,ls, scp等命令。 里面涉及到輸入密碼的交互式場景,這個(gè)時(shí)候expect命令的巨大功效就出來了,下面是一個(gè)比較經(jīng)典腳本實(shí)現(xiàn):
#!/usr/bin/tclshpackage require Expectset host_ip1 [lindex $argv 0]set host_usr [lindex $argv 1]set host_pwd [lindex $argv 2]spawn ssh $host_usr@$host_ip1set timeout 60expect { -re "password" {send "$host_pwd/n"} -re "yes/no" {send "yes/n";exp_continue} # 有的時(shí)候輸入幾次密碼來確認(rèn),exp_continue}expect "#"send "ls /home/${host_user} | tee -a /tmp/ls.txt /r"expect "#"send "exit/r"expect eof總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)武林網(wǎng)的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
新聞熱點(diǎn)
疑難解答
圖片精選