1. 程式人生 > >shell腳本基礎(八)

shell腳本基礎(八)

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 [email protected]:/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 [email protected]:/tmp/12.txt /tmp/
[email protected]‘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 [email protected]:/tmp/123.txt
[email protected]‘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

shell腳本基礎(八)