Automatically sync files
#!/usr/bin/expect set passwd "123456" spawn rsync -av root@192.168.133.132:/tmp/12.txt /tmp/ expect { "yes/no" { send "yes\r"} "password:" { send "$passwd\r" } } expect eof
Specify host and files to sync
#!/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 chmod +x ex4.sh ./ext4.sh 192.168.133.132 "/tmp/12.txt"
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.
- The realization idea
is to have a template machine first, 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. - Core command
rsync -av --files-from=list.txt /root@host:/
Implementation of a file distribution system
• rsync.expect content #!/usr/bin/expect set passwd "123456" set host [lindex $argv 0] set file [lindex $argv 1] spawn rsync -avR --files-from=$file / root@$host:/ expect { "yes/no" { send "yes\r"} "password:" { send "$passwd\r" } } expect eof
If it is not guaranteed that the corresponding machine also has the same file path plus -R to create it automatically
list.txt content (ensure that the file list path is also available on the other machine )
/tmp/12.txt /root/shell/1.sh 。。。。
ip.list content
192.168.133.132 192.168.133.133 ......
If the passwords of multiple hosts are different, key authentication can be performed .
rsync.sh content
#!/bin/bash for ip in `cat ip.list` doecho $ip ./rsync.expect $ip list.txt done
Execute: chmod a+x rsync.sh
./rsync.sh
Batch remote execution of commands
exe.sh content
#!/bin/bash for ip in `cat ip.list` doecho $ip ./exe.expect $ip "w;free -m;ls /tmp" done