2018-4-27 18周2次课 分发系统-expect讲解(下)

20.31 expect脚本同步文件


·自动同步文件

1.png

[root@localhost sbin]# chmod a+x 4.expect
[root@localhost sbin]# ./4.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  76.00 bytes/sec
total size is 5  speedup is 0.04
[root@localhost sbin]# cat /tmp/12.txt
1212

(脚本结尾需要加 expect eof 或者 interact )





20.32 expect脚本指定host和要同步的文件


·指定host和要同步的文件

2.png

(file一定要写绝对路径)

[root@localhost sbin]# chmod a+x 5.expect
[root@localhost sbin]# ./5.expect 192.168.65.129 "/tmp/12.txt"
spawn rsync -av /tmp/12.txt [email protected]:/tmp/12.txt
[email protected]'s password:
sending incremental file list
sent 31 bytes  received 12 bytes  86.00 bytes/sec
total size is 5  speedup is 0.12





20.33 构建文件分发系统


·需求背景对于大公司而言,肯定时不时会有网站或者配置文件更新,而且使用的机器肯定也是好多台,少则几台,多则几十甚至上百台。所以,自动同步文件是至关重要的。

·实现思路首先要有一台模板机器,把要分发的文件准备好,然后只要使用expect脚本批量把需要同步的文件分发到目标机器即可。

·核心命令rsync -av --files-from=list.txt  /  root@host:/


·文件分发系统的实现


·rsync.expect 内容

3.png


·/tmp/list.txt内容

4.png


·ip list 文件:/tmp/ip.txt

192.168.65.129


·rsync.sh内容

5.png

[root@localhost sbin]# chmod a+x rsync.expect
[root@localhost sbin]# sh -x rsync.sh
++ cat /tmp/ip.txt
+ for ip in '`cat /tmp/ip.txt`'
+ echo 192.168.65.129
192.168.65.129
+ ./rsync.expect 192.168.65.129 /tmp/list.txt
spawn rsync -av --files-from=/tmp/list.txt / [email protected]:/
[email protected]'s password:
building file list ... done
root/
root/111/222/
root/111/222/test.txt
root/shell/
root/shell/01.sh
tmp/
tmp/12.txt
sent 369 bytes  received 81 bytes  900.00 bytes/sec
total size is 71  speedup is 0.16

(在129机器上也可以查看到同步过去的文件)


·思路:

执行 rsync.expect 脚本并且要传递两个参数

而其中之一是多个ip中的一个,把 ip 写到一个文本中,for 循环依次去读一个ip,并传递到脚本中去

在 shell 脚本中写此 for 循环,可以执行

把需要同步的文件绝对目录写入到 list.txt 中,这样可以将需要同步的目录依次同步到 ip.txt 中的机器





20.34 批量远程执行命令


·exe.expect 内容

6.png


·exe.sh 内容

7.png


·执行脚本

[root@localhost sbin]# sh exe.sh
192.168.65.129
spawn ssh [email protected]
[email protected]'s password:
Last login: Thu Apr 26 00:10:01 2018 from 192.168.65.128
[root@localhost ~]# w;free -m;ls /tmp
00:13:10 up  1:35,  2 users,  load average: 0.01, 0.02, 0.05
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    192.168.65.1     22:38   23:42   0.23s  0.23s -bash
root     pts/1    192.168.65.128   00:13    0.00s  0.05s  0.03s w
total        used        free      shared  buff/cache   available
Mem:            976         589         116           6         271         212
Swap:          2047           0        2047
12.txt         systemd-private-606af9ac8a8c48d8bd2a5d7938fec6e8-chronyd.service-Tv9azy
alex.sock     systemd-private-606af9ac8a8c48d8bd2a5d7938fec6e8-vgauthd.service-aii2pH
mysql.sock     systemd-private-606af9ac8a8c48d8bd2a5d7938fec6e8-vmtoolsd.service-6NjtpQ
php-fcgi.sock  test.com.log

猜你喜欢

转载自blog.51cto.com/11530642/2107911