您的位置:首页 > 其它

expect应用

2014-01-19 01:48 274 查看
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 root@192.168.1.179:/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 eof
exit -onexit {
send_user "Oldboy say good bye to you!\n"
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  password expect