20.31 expect脚本同步文件
expect通过与rsync结合,可以在一台机器上把文件自动同步到多台机器上
编写脚本
[root@linux-5 ~]# cd /usr/local/sbin
[root@linux-5 sbin]# vim 4.expect
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av root@192.168.88.10:/root/1.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
注:expect eof的作用同interact,可以为spwan所执行的命令提供足够的时间执行,不会马上退出expect,从而导致命令尚未执行完毕而退出的情况(尤其是文件传输的命令)
脚本授权
[root@linux-5 sbin]# chmod a+x !$
chmod a+x ./4.expect
执行脚本
[root@linux-5 sbin]# ./4.expect
spawn rsync -av root@192.168.88.10:/root/1.txt /tmp/
receiving incremental file list
1.txt
sent 43 bytes received 96 bytes 278.00 bytes/sec
total size is 6 speedup is 0.04
expect: spawn id exp6 not open
while executing
"expect eof"
(file "./4.expect" line 8)
结果验证
[root@linux-5 sbin]# cat /tmp/1.txt
12345
20.32 expect脚本指定host和要同步的文件
通过带参数的方式为指定的地址同步指定的文件
编写脚本
#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0] #第一个参数
set file [lindex $argv 1] #第二个参数
spawn rsync -av $file root@$host:$file
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
脚本授权
[root@linux-5 sbin]# chmod a+x 5.expect
执行脚本
[root@linux-5 sbin]# ./5.expect 192.168.88.10 /tmp/1.txt
spawn rsync -av /tmp/1.txt root@192.168.88.10:/tmp/1.txt
sending incremental file list
1.txt
sent 96 bytes received 35 bytes 262.00 bytes/sec
total size is 6 speedup is 0.05
expect: spawn id exp6 not open
while executing
"expect eof"
(file "./5.expect" line 10)
结果验证
[root@linux-10 ~]# cat /tmp/1.txt
12345
20.33 构建文件分发系统
20.34 批量远程执行命令
转载至链接:https://my.oschina.net/u/3804357/blog/1860414