linux学习第七十篇:expect脚本同步文件,expect脚本指定host和要同步的文件,构建文件分发系统,批量远程执行命令

expect脚本同步文件

  • 自动同步文件
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av root@192.168.133.132:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
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/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
  • ip.list内容,为需要同步的远程机器IP
192.168.133.132
192.168.133.133
  • list.txt内容,为同步的文件路径
/tmp/12.txt
/root/1.sh
/root/111/222/lll.txt
  • rsync.sh 内容
#!/bin/bash
for ip in `cat /tmp/ip.list` #要输入文档的绝对路径
do
    echo $ip
    ./rsync.expect $ip /tmp/list.txt
done

这里写图片描述

批量远程执行命令

  • 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"}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
  • exe.sh 内容
#!/bin/bash
for ip in `cat /tmp/ip.list`
do
    echo $ip
    ./exe.expect $ip ;w;free -m;ls /tmp
done

这里写图片描述

扩展:
shell多线程 http://blog.lishiming.net/?p=448

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值