一、expect脚本同步文件
编辑脚本文件
vim test4.expect
在文件中添加如下内容
#!/usr/bin/expect
set passwd "12345"
spawn rsync -av root@192.168.177.200:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
执行脚本之前需要加上权限
chmod a+x test4.expect
./test4.expect
二、 expect脚本指定host和要同步的文件
编辑脚本文件
vim test5.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 test5.expect
./test5.expect
三、构建文件分发系统
•需求背景
对于大公司而言,肯定时不时会有网站或者配置文件更新,而且使用的机器肯定也是好多台,少则几台,多则几十甚至上百台。所以,自动同步文件是至关重要的。
• 实现思路
首先要有一台模板机器,把要分发的文件准备好,然后只要使用expect脚本批量把需要同步的文件分发到目标机器即可。
• 核心命令
rsync -av --files-from=list.txt / root@host:/
1.定义脚本文件
vim rsync.expect
2.添加如下的内容
#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -av --files-from=$file / root@$host:/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
3.定义file list文件
vim /tmp/list.txt
内容填写要同步文件的绝对路径即可
4.定义ip list
vim /tmp/iplist
内容填写IP地址即可
5.创建rsync shell脚本
vim rsync.sh
添加如下内容
rsync.sh 内容
#!/bin/bash
for ip in `cat ip.txt`
do
echo $ip
./rsync.expect $ip list.txt
done
执行脚本即可
四、批量远程执行命令
1.编辑脚本
vim exe.expect
2.写入如下的脚本
#!/usr/bin/expect
set host [lindex $argv 0]
set passwd "asdfg"
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"
4.添加权限
chmod a+x exe.expect
5.编辑shell脚本
#!/bin/bash
for ip in `cat /tmp/ip.txt`:
do
./exe.expect $ip "hostname"
done