shell中使用expect命令進行遠程執(zhí)行命令腳本
expect是用來實現自動交互功能的工具之一,使用expect-send來實現交互過程。
注意:
1、腳本的執(zhí)行方法與bash shell不一樣,比如:expect example.sh
2、向一個腳本傳遞參數時,bash shell是使用$1,$2...來接收參數的;而expect則將腳本的執(zhí)行參數保存在數組$argv中,在腳本中一般將其賦值給變量:set 變量名 [lindex $argv 參數]
#!/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" # 進入指定的機器后,就可執(zhí)行相應的命令或者腳本 interact #expect eof
注意:若登陸后便退出遠程終端,則寫expect eof
即可。
3、執(zhí)行腳本
expect autologin.sh 192.168.1.240 root
很多時候,需要用expect命令實現登錄遠端服務器執(zhí)行簡單命令,諸如:重啟服務器,ftp,ls, scp等命令。 里面涉及到輸入密碼的交互式場景,這個時候expect命令的巨大功效就出來了,下面是一個比較經典腳本實現:
#!/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
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
Linux shell 實現用for循環(huán)100次的方法
今天小編就為大家分享一篇Linux shell 實現用for循環(huán)100次的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06深入理解Linux shell中2>&1的含義(全網最全,看完就懂)
這篇文章主要介紹了深入理解Linux shell中2>&1的含義,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09