接着写一个稍微复杂点的脚本,分发文件到指定服务器脚本。
首先我们要知道远程分发文件的命令格式
scp 源文件 验证用户@远程主机:远程目录[root@130 ~]# scp auto_yes.exp root@192.168.222.131:/tmp/
需求就是通过脚本来实现发送,不需要输入密码,也就是验证用户是固定的还有密码是固定的,其他的主机IP和目的路径是不固定的,我们通过设置为位置变量来实现自定义化。最终实现的效果:
[root@DECMDB01 ~]# expect batch_file.exp 172.18.0.20 yezi.txt /tmp/spawn scp yezi.txt root@172.18.0.20:/tmp/yezi.txt 100% 343 0.3KB/s 00:00
全程不需要输入密码,而只需要指定主机IP和发送的文件已经发送到目的主机的目的路径,其他的密码和验证用户都已经在脚本中设置好了
看一下脚本:
#!/usr/bin/expectif { $argc != 3 } {puts "Please use: 'expect $argv0 ip source_file d_path'"exit}set ip [lindex $argv 0]set sfile [lindex $argv 1]set dpath [lindex $argv 2]set password "rxadmin123"#spawn scp $sfile root@$ip:$dpathexpect {"*yes/no" {exp_send "yes\n";exp_continue}"*password" {exp_send "$password\n"}}expect eof
标记分析一下:
#!/usr/bin/expectif { $argc != 3 } { ##先做一个判断,如果位置变量不是3个则提示"Please...d_path",这里的argc和Shell里的$#是一样的puts "Please use: 'expect $argv0 ip source_file d_path'"##puts后面提示内容,用""标记exit ##退出判断}set ip [lindex $argv 0]##设置ip变量,这里的argv 0等于Shell里的$1set sfile [lindex $argv 1]##设置sfile变量,这里的argv 1等于Shell里的$2set dpath [lindex $argv 2]##设置dpath变量,这里的argv 1等于Shell里的$3set password "123456"##设置密码123456为$password#spawn scp $sfile root@$ip:$dpathexpect {"*yes/no" {exp_send "yes\n";exp_continue} ##这里的exp_send和send类似"*password" {exp_send "$password\n"}}expect eof ##结束脚本
!!! 需要注意的是里面的每个符号都为英文符号,{}和""以及;的用法都是固定格式,请牢记,建议脚本复制后故意删除符号进行测试符号的作用