Linux学习总结(六十四)expect脚本下

一 文件分发系统

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

  • 创建expect脚本,调用上面的核心命令,实现文件同步
  • 创建文件列表和ip列表,指定要分发的文件路径和分发对象主机。
  • 创建一个shell脚本,对上面指定的ip列表进行循环遍历,并调用expect脚本分发文件。
    代码如下:
    1 vim rsync.expect
    #!/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 两个列表文件

    vim filelist.txt
    /root/123.txt
    /usr/local/sbin/lvs_dr.sh
    ...
    vim iplist.txt
    192.168.226.130
    192.168.225.131
    ...

    3 vim rsync.sh

    #!/bin/bash
    for ip in `cat iplist.txt`;do
    ./rsync.expect $ip filelist.txt
    done

    二 多台机器的命令分发

    仿照上面的思路,就是用expect脚本在远程主机上执行命令,再用shell脚本对远程主机ip做一个循环,再调用expect脚本即可。
    1 编写expect脚本
    vim command.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"

    2 编写ip列表文件

    vim iplist.txt
    192.168.226.130
    192.168.226.131
    ...

    3 编写shell循环脚本

    vim command.sh
    for ip in `cat iplist.txt`;do
    ./command.expect $ip "ls"
    done

    备注:用expect脚本上线代码仅仅是一种思路,如果采用了秘钥认证,当然可以直接使用shell脚本调用rsync命令,再做一个循环就可以。后续还需要学习更高级的工具来上线代码,比如git。

猜你喜欢

转载自blog.51cto.com/12606610/2130062