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

20.31 expect脚本同步文件;20.32 expect脚本指定host和要同步的文件;20.33 构建文件分发系统;20.34 批量远程执行命令

20.31 expect脚本同步文件

自动同步文件

1. 同步远程机器149/tmp/12.txt文件 到本机/tmp/下 :

[root@aminglinux-128 ~]#  vim 4.expect
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av [email protected]:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}expect eof

2. 增加4.expect脚本x权限 

[root@aminglinux-128 ~]# chmod a+x 4.expect

3. 执行4.expect脚本(自动同步文件) 

[root@aminglinux-128 ~]# ./4.expect

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

1. 执行脚本需要:指定host(主机ip)和要同步的文件

[root@aminglinux-128 ~]# vim 5.expect
#!/usr/bin/expect
set passwd "admin"
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

2. 增加5.expect脚本x权限 

[root@aminglinux-128 ~]# chmod a+x 5.expect

3. 执行5.expect脚本(执行一次只能同步一个文件!) 

 ./5.expect 192.168.193.128 "tmp/12.txt"


扫描二维码关注公众号,回复: 3344306 查看本文章

20.33 构建文件分发系统

shell项目-分发系统-构建文件分发系统

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

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

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

文件分发系统的实现

1. 创建rsync.expect核心脚本 :

(从本地/根目录  到远程/根目录)

[root@aminglinux-128 ~]# vim rsync.expect

(远程ip机器密码需要和本地一致;也可以做用户认证,即可不用密码一致,安全)

#!/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

2. 创建本地同步文件列表文件 

(本地同步远程机器文件;绝对路径)

[root@aminglinux-128 ~]#  vim /tmp/file.list
/tmp/12.txt
/root/1.txt

3. 创建远程机器ip列表文件 

(远程ip机器密码需要和本地一致;也可以做用户认证,即可不用密码一致,安全)

[root@aminglinux-128 ~]#  vim /tmp/ip.list
192.168.193.128
127.0.0.1

4. 创建 rsync.sh循环脚本 :

(对应指定: 同步到远程机器ip列表文件 本地同步文件列表文件)

[root@aminglinux-128 ~]#  vim rsync.sh
#!/bin/bash
for ip in `cat /tmp/ip.list`
do
    ./rsync.expect $ip /tmp/file.list
done

5. 增加rsync.sh脚本x权限 

chmod a+x rsync.sh

6. 执行rsync.sh脚本

[root@aminglinux-128 ~]# sh -x rsync.sh
++ cat /tmp/ip.list
+ for ip in '`cat /tmp/ip.list`'
+ ./rsync.expect 192.168.193.128 /tmp/file.list
rsync.sh:行4: ./rsync.expect: 权限不够
+ for ip in '`cat /tmp/ip.list`'
+ ./rsync.expect 127.0.0.1 /tmp/file.list
rsync.sh:行4: ./rsync.expect: 权限不够

20.34 批量远程执行命令

1. 创建exe.expect核心脚本:

[root@aminglinux-128 ~]# vim exe.expect
#!/usr/bin/expect
set host [lindex $argv 0]
set passwd "admin"
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"

2. 增加exe.expec脚本x权限 

[root@aminglinux-128 ~]#  chmod a+x exe.expect

3. 创建exe.sh脚本 :

(设定 访问远程机器执行的命令)

[root@aminglinux-128 ~]# vim exe.sh
#/bin/bash
for ip in `cat /tmp/ip.list`
do
   ./exe.expect $ip "ls"
done

4. 执行exe.sh脚本 :

[root@aminglinux-128 ~]# sh exe.sh


猜你喜欢

转载自blog.51cto.com/13107353/2285229