expect脚本同步文件,expect脚本指定host和要同步的文件,构建文件分发系统,批量远程执行

expect脚本同步文件

自动同步文件
#!/usr/bin/expect
set passwd "目标机器密码"
spawn rsync -av root@目标机器ip:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof

然后赋予权限
chmod a+x 4.expect

[root@linletao-001 shell]# ./4.expect
spawn rsync -av [email protected]:/tmp/12.txt /tmp/
[email protected]'s password:
receiving incremental file list

sent 11 bytes received 36 bytes 94.00 bytes/sec
total size is 5 speedup is 0.11
执行成功

如果在结尾处不加expect eof,他就会不执行而直接退出。

expect脚本指定host和要同步的文件
指定host和要同步的文件
#!/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

构建文件分发系统

需求背景对于大公司而言,肯定时不时会有网站或者配置文件更新,而且使用的机器肯定也是好多台,少则几台,多则几十甚至上百台。所以,自动同步文件是至关重要的。 实现思路首先要有一台模板机器,把要分发的文件准备好,然后只要使用expect脚本批量把需要同步的文件分发到目标机器即可。

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

文件分发系统的实现
rsync.expect 内容
#!/usr/bin/expectset
passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -avR --files-from=$file / root@$host:/ 这里的大写R的意义是,如果对方机器上没有这个目录,那么他会自动创建。
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
然后给他执行权限。
chmod a+x rsync.expect

然后定义$file,也就是文件列表,我们要注意的是,文件路径一定要在另一台机器上也要有
比如我们将它写到tmp下
vim /tmp/list.txt
然后我们再定义一个ip列表,也写到tmp下
vim /tmp/ip.txt
还要注意的是要同步的两台设备密码必须是一样的。

然后再创建一个rsync.sh
rsync.sh 内容
#!/bin/bash
for ip in cat ip.list
do
echo $ip
./rsync.expect $ip
list.txt
done
更改权限
chmod z+x rsync.sh

批量远程执行命令

exe.expect 内容
#!/usr/bin/expect
et 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"
赋予权限chmod z+x exe.expect

exe.sh 内容
#!/bin/bash
for ip in cat ip.list
do
echo $ip
./exe.expect $ip "w;free -m;ls /tmp"
done
赋予权限 chmod z+x exe.sh

猜你喜欢

转载自blog.51cto.com/13067688/2126185