expect是用來實現自動交互功能的工具之一,使用expect-send來實現交互過程。
注意:
1、腳本的執行方法與bash shell不一樣,比如:expect example.sh
2、向一個腳本傳遞參數時,bash shell是使用$1,$2...來接收參數的;而expect則將腳本的執行參數保存在數組$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"
# 進入指定的機器后,就可執行相應的命令或者腳本
interact
#expect eof
注意:若登陸后便退出遠程終端,則寫expect eof
即可。
3、執行腳本
expect autologin.sh 192.168.1.240 root
很多時候,需要用expect命令實現登錄遠端服務器執行簡單命令,諸如:重啟服務器,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
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
您可能感興趣的文章:- Shell腳本中管道的幾種使用實例講解
- Shell腳本用for循環遍歷參數的方法技巧
- Shell腳本中awk指令的用法
- Shell中字符串排序的幾種方法
- Shell中整數計算的幾種方式
- 一條命令讓你明白shell中read命令的常用參數
- Shell中統計字符串中單詞的個數的幾種方法
- Shell中去除字符串里的空格或指定字符的方法
- Shell中去除字符串前后空格的方法
- Shell腳本從文件中逐行讀取內容的幾種方法實例