天天看点

expect应用

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

expect应用

注: 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

上一篇: expect使用
下一篇: expect用法

继续阅读