- Shell 项目-分发系统-expect
- yum install -y expect
- 以下所有脚本保存后都需要更改权限才能正常执行
- 自动远程登陆,并执行命令
- #!/usr/bin/expect
- set host “192.168.xxx.xxx”
- set passwd “123456”
- spawn ssh root@$host
- expect { “yes/no” { send “yes\r”; exp_contonue} “password:” { send “$passwd\r” }
- }
- interact
- #interact 会使你停留在当下状态
- #expect eof 短暂停留 2 秒后退出
- #当去除 interact 和 expect eof 脚本会在你登录的同时退出,也就不存在执行任何命令了
- 自动远程登录后,执行命令并退出
- #!/usr/expect
- set user “root”
- set passwd “123456”
- spawn ssh $user@192.168.xxx.xxx
- expect { “yes/no” {send “yes\r”; exp_continue}
- “password:” {send “$passwd\r” }
- }
- expect “]*”
- send “touch /tmp/12.txt\r” expect “]*”
- send “echo 1212 > /tmp/12.txt\r” expect “]*”
- send “exit\r” 传递参数
- #!/usr/bin/expect
- set user [lindex $argv 0]
- set host [lindex $argv 1]
- set passwd “123456”
- set cm [lindex $argv 2]
- spawn ssh $user@host
- expect { “yes/no” { send “yes\r” } “password:” { send “$passwd\r” }
- }
- expect “]*”
- send “$cm\r” expect “]*”
- send “exit\r” 自动同步文件
- #!/usr/bin/expect
- set passwd “123456”
- spawn rsync -av root@192. 168. xxx. xxx: /t mp/12. t xt /t mp/
- expect { “yes/no” { send “yes\r” } “password:” { send “$passwd\r” }
- }
- expect eof
- 指定 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 “$passd\r” }
- }
- expect eof
- 需求背景
- 对于大公司而言,肯定时不时会有网站或者配置文件更新,而且使用的机器肯定也是许多
- 台,少则几台,多则几十上百。所有,自动同步文件至关重要。
- 实现思路
- 首先要有一台模板机器,把要分发的文件准备好,然后只要使用 expect 脚本批量把需要同
- 步的文件分发到目标机器即可。
- 核心命令
- rsync -av --file-from=list.txt / root@host:/
- 文件分发系统的实现
- rsync.expect 内容如下
- #!/usr/bin/expect
- set passwd “123456”
- set host [lindex $argv 0]
- set file [lindex $argv 1]
- spawn reync -av --files-from=$file /root@$host:/
- expect { “yes/no” { send “yes\r” } “password:” { send “$passwd\r” }
- }
- expect eof
- ip.list 内容如下
- 192.168.xxx.xxx
- 192.168.xxx.xxx
- ..... rsync.sh 内容如下
- #!/bin/bash
- for ip in ‘cat ip.list’ do
- echo $ip
- ./rsync.expect $ip list.txt
- done
- 命令批量执行
- exe.expect 内容如下
- #!/usr/bin/expect
- set host [linex $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 “exid\r”
- exe.sh 内容如下
- #!/bin/bash
- for ip in ‘cat ip.list’ do
- echo $ip
- ./exe.expect $ip “w;free -m;ls /tmp” done
转载于:https://my.oschina.net/u/4095969/blog/3064522