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就是直接退出,加個-onexit {}可以做一些退出之後執行的指令 如oldboy-8.exp腳本:
#!/usr/bin/expect
send_user "usage: expect scp-expect.exp file host dir\n"
}
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
-timeout 20
timeout {puts "expect connect timeout,pls contact oldboy."; return}
expect eof