1,expect脚本同步文件。
使用rsync工具同步文件。vi 4.expect
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av root@192.168.177.132:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
# chmod a+x 4.expect
# ./4.expect
spawn rsync -av root@192.168.177.132:/tmp/12.txt /tmp/
root@192.168.177.132's password:
receiving incremental file list
12.txt
sent 43 bytes received 97 bytes 93.33 bytes/sec
total size is 5 speedup is 0.04
2,expect脚本指定host和要同步的文件。
同步单个文件。vi 5.expect
#!/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 a+x 5.expect
# ./5.expect 192.168.177.132 "/tmp/12.txt"
spawn rsync -av /tmp/12.txt root@192.168.177.132:/tmp/12.txt
root@192.168.177.132's password:
sending incremental file list
sent 45 bytes received 12 bytes 114.00 bytes/sec
total size is 5 speedup is 0.09
3,构建文件分发系统。
需求背景:对于大公司而言,肯定时不时会有网站或者配置文件更新,而且使用的机器肯定也是好多台,少则几台,多则几十甚至上百台。所以,自动同步文件是至关重要的。
实现思路:首先要有一台模板机器,把要分发的文件准备好,然后只要使用expect脚本批量把需要同步的文件分发到目标机器即可。
核心命令:rsync -av --files-from=list.txt / root@host:/
vi rsync.expect
#!/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
ip.list内容
192.168.177.132
127.0.0.1
rsync.sh 内容
#!/bin/bash
for ip in `cat /tmp/ip.list`
do
echo $ip
./rsync.expect $ip /tmp/file.list
done
4,批量远程执行命令。
exe.expect 内容
#!/usr/bin/expect
set host [lindex $argv 0]
set passwd "123456"
set cm [lindex $argv 1]
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
exe.sh 内容
#!/bin/bash
for ip in `cat ip.list`
do
echo $ip
./exe.expect $ip "w;free -m;ls /tmp"
done