shell脚本基础(八)

1、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

2、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

3、构建文件分发系统

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

一、文件分发系统的实现

[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
#来建立路径nginx

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

相关文章
相关标签/搜索