expect的安裝
yum -y install expect
注:expect最簡單的實例就是ssh連接回有交互式,爲了讓其自動,以下腳本能實現自動登錄功能如下:
#!/usr/bin/expect
spawn ssh 192.168.1.117 ifconfig eth0
set timmeout 60
expect "*password:" ##等待捕捉出現*password:
send "12344\n" ##發送字符
expect eof
exit
注:exp__send就是send一樣
在ssh第一次連接的時候會提示yes/no的交互式的,不用這個關鍵詞會出錯,用exp_continue解決,-timeout 意思就是超過X秒就會執行下面對應的那行timeout “puts xxxx“命令,這裏的puts相當於echo? ,;return意思就是返回
實例腳本:oldboy-4.exp
注: send_user參數也和echo一樣,以下爲
oldboy-6.exp腳本
#!/usr/bin/expect
###################################
#this scripts is created by oldboy
###################################
if { $argc != 3 } {
send_user "usage: expect scp-expect.exp file host dir\n"
exit
}
#define var
set file [lindex $argv 0]
set host [lindex $argv 1]
set dir [lindex $argv 2]
set password "123456"
spawn scp -P22 -p $file root@$host:$dir
expect {
"yes/no" {send "yes\r";exp_continue}
"*password" {send "$password\r"}
}
expect eof
exit
exit就是直接退出,加個-onexit {}可以做一些退出之後執行的命令 如oldboy-8.exp腳本:
#!/usr/bin/expect
if { $argc != 3 } {
send_user "usage: expect scp-expect.exp file host dir\n"
exit
}
set file [lindex $argv 0] # 設置變量名file代表參數1
set host [lindex $argv 1] #設置host爲參數2
set dir [lindex $argv 2] #設置dir爲參數3
set password "123456" #設置set 變量名 變量內容spawn scp -P22 -r -p $file root@$host:$dir
#spawn scp -P 22 -r -p /root/.ssh [email protected]:/root/
set timeout 60
expect {
-timeout 20
"yes/no" {send "yes\r";exp_continue}
"*password" {send "$password\r"}
timeout {puts "expect connect timeout,pls contact oldboy."; return}
}
expect eofexit -onexit {
send_user "Oldboy say good bye to you!\n"
}