Shell script foundation (8)

1. Expect script to synchronize files

[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

2. The expect script specifies the host and the files to be synchronized

[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

3. Build a file distribution system

Demand background: For large companies, there must be website or configuration file updates from time to time, and there must be many machines used, ranging from a few to dozens or even hundreds. So, automatically syncing files is crucial.
Implementation idea: First, you need a template machine, prepare the files to be distributed, and then just use the expect script to distribute the files that need to be synchronized to the target machine in batches. The
core command:rsync -av --files-from=list.txt / root@host:/

1. Implementation of a file distribution system


[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 #If
you are not sure about the remote path, you can add option -R
# to create the path

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324927881&siteId=291194637