expect

                       expect 


expect是可以实现服务器之间自动交互的工具


  I、 expect安装

expect工具是否安装:

          在Linux系统命令行执行which expect,若返回/usr/bin/expect表示已经安装过,反之则没有安装。

expect安装说明:

         安装有RPM包可下载expect的RPM包,依赖tcl包,所以tcl也要一并安装。

expect安装步骤:

          1、先下载expect,tcl,tcl-devel包。

          2、传到要安装的系统上(主意包的版本)。

          3、可直接执行rpm -ivh package-name(安装顺序tcl、tcl-devel、expect)。  


  II、expect_scp脚本

[root@ora exp]# cat expect_scp 

#!/usr/bin/expect       

#

set timeout 3

set host [lindex $argv 0]

set username [lindex $argv 1]

set password [lindex $argv 2]

set src_file [lindex $argv 3]

set dest_file [lindex $argv 4]

 

spawn scp $username@$host:$src_file $dest_file

 expect "(yes/no)?"{send "yes\n"}

 expect "*assword:"{send "$password\n"}

 expect "100%"

expect eof

You have new mail in /var/spool/mail/root

[root@ora exp]# 

    

     III、测试上面脚本

[root@ora exp]# ls

01scp.py  expect_scp  mult.sh  mult.sh.bak  scp01.exp  scp.py

[root@ora exp]# ./expect_scp 192.168.168.171 root qw1501as /root/1q ./

spawn scp [email protected]:/root/1q ./

reverse mapping checking getaddrinfo for bogon [192.168.168.171] failed - POSSIBLE BREAK-IN ATTEMPT!

[email protected]'s password: 

1q                                                                                                                   100%   84     0.1KB/s   00:00    

[root@ora exp]# 

 

对II注释:

     set 在此处是定义变量的

     set host [lindex $argv 0]     //host是变量名,在此处定义的是IP。[]中是给变量传递的参数,格式是lindex $argv # 在此处的“#”是数字0表示第一个参数依次往后1第二个。。。

     set username [lindex $argv 1]  //username 在此处定义用户名

     set password [lindex $argv 2]  //password 在此处定义密码

     set src_file [lindex $argv 3]  //src_file 在此处定义的是源文件的位置

     set dest_file [lindex $argv 4] //dest_file 在此处定义的是目标文件的位置

spawn scp $username@$host:$src_file $dest_file

         //这一行引用了scp命令,这个scp命令要在expect环境下执行前面需要加spawn 

expect "(yes/no)?"  //expect能匹配到sh环境内的字符,支持正则表达式.

send "yes\n"  //send能够把后面的数据传给sh进程

expect和send结合,较清晰的体现出了自动交互功能,说白了就是expect匹配到出现的字符,到该要手动输入的字符交给send来完成。

expect "100%" //匹配到  100%

expect eof //结束

对III注释:

     当执行expect脚本时,可以./expect_scp 参数1 参数2 参数3...此处的参数的顺序要和expect的脚本中定义的变量的参数的顺序一致。


要是批量scp的话需要再写个shell脚本,在服务器上,执行之后即可批量传输了。


你可能感兴趣的:(expect)