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

20.31 expect脚本同步文件

自动同步文件

#!/usr/bin/expect
set passwd "123456"
spawn rsync -av root@192.168.192.135:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
expect eof
}

//expect eof 不加这句 还没来得及传输就退出了

20.32 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
}


./5.expect 192.168.192.135 "/tmp/99.txt"   //只能写绝对路径

20.33 构建文件分发系统

需求背景
对于大公司而言,确定时不时会有网站或者配置文件更新,并且使用的机器确定也是好多台,少则几台,多则几十甚至上百台。因此,自动同步文件是相当重要的。
实现思路
首先要有一台模板机器,把要分发的文件准备好,而后只要使用expect脚本批量把须要同步的文件分发到目标机器便可。
核心命令
rsync -avR --files-from=list.txt  /  root@host:/

// R 若是目标目录不存在, 能够建立目标主机的级联路径

文件分发系统的实现

cd /usr/local/sbin

rsync.expect 内容

chmod a+x rsync.expect


#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -avP --files-from=$file / root@$host:/
expect {
"yes/no" { send "yes\r";exp_continue}
"password:" { send "$passwd\r" }
}
expect eof

vim /tmp/list.txt 内容


/tmp/12.txt
/root/shell/01.sh
/root/shell/03.sh
....

vim /tmp/ip.txt  内容


192.168.192.135
192.168.192.136
......

vim rsync.sh 内容

chmod a+x rsync.sh


for ip in `cat /tmp/ip.txt`
do
    echo $ip
    ./rsync.expect $ip /tmp/list.txt
done



测试

20.34 批量远程执行命令

exe.expect 内容

chmod a+x 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";exp_continue}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
 
exe.sh 内容

#!/bin/bash
for ip in `cat /tmp/ip.txt`
do
    echo $ip
    ./exe.expect $ip "w;free -m;ls /tmp"
done

测试

sh -x exe.sh
相关文章
相关标签/搜索