shell脚本基础(八)

一、expect脚本同步文件

[root@zlinux-01 ~]# cd /usr/local/sbin/
[root@zlinux-01 sbin]# ls
01.expect  02.expect  03.expect  check_ng.sh  lvs_dr.sh  lvs_nat.sh  mon  nginx_log_rotate.sh
[root@zlinux-01 sbin]# vim 04.expect            //自动同步脚本

#!/usr/bin/expect
set passwd "rootroot"
spawn rsync -av root@192.168.242.129:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r"}
}
expect eof

[root@zlinux-01 sbin]# ./04.expect 
spawn rsync -av root@192.168.242.129:/tmp/12.txt /tmp/
root@192.168.242.129's password: 
receiving incremental file list
12.txt

sent 30 bytes  received 84 bytes  228.00 bytes/sec
total size is 5  speedup is 0.04
[root@zlinux-01 sbin]# ls /tmp/12.txt 
/tmp/12.txt

二、expect脚本指定host和要同步的文件

[root@zlinux-01 sbin]# vim 05.expect 

#!/usr/bin/expect
set passwd "rootroot"
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@zlinux-01 sbin]# chmod a+x 05.expect
[root@zlinux-01 sbin]# touch /tmp/123.txt
[root@zlinux-01 sbin]# ./05.expect 192.168.242.129 /tmp/123.txt
spawn rsync -av /tmp/123.txt root@192.168.242.129:/tmp/123.txt
root@192.168.242.129's password: 
sending incremental file list
123.txt

sent 71 bytes  received 31 bytes  204.00 bytes/sec
total size is 0  speedup is 0.00

三、构建文件分发系统

需求背景:对于大公司而言,肯定时不时会有网站或者配置文件更新,而且使用的机器肯定也是好多台,少则几台,多则几十甚至上百台。所以,自动同步文件是至关重要的。
实现思路:首先要有一台模板机器,把要分发的文件准备好,然后只要使用expect脚本批量把需要同步的文件分发到目标机器即可
核心命令:rsync -av --files-from=list.txt / root@host:/

1、文件分发系统的实现


[root@zlinux-01 sbin]# vim rsync.expect

#!/usr/bin/expect
set passwd "rootroot"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -avR $file root@$host:$file
#如果不确定远程路径可以 加选项 -R
#来创建路径

expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r"}
}
expect eof

转载于:https://blog.51cto.com/3069201/2108368

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值