expect 分发
yum install -y expect
1. 自动远程登录
- #! /usr/bin/expect
- set host "192.168.133.132" // 定义变量 host
- set passwd "123456"
- spawn ssh root@$host //spawn 后面跟系统 shell 命令, 远程登录
- expect {"yes/no" { send "yes\r"; exp_continue} // 初次登录机器会提示 yes/no, 再次登录不会是因为 / root/.ssh/known_hosts 有记录. 表示有 yes/no 时, 做括号中动作, exp_continue 表示继续
- "password:" { send "$passwd\r" }
- }
- interact // 保持登录在机器上, 若用 expect eof, 则停留一会儿退出
需要给文件执行权限
2. 自动远程登录后, 执行命令并退出
- #!/usr/bin/expect
- set user "root"
- set passwd "123456"
- spawn ssh $user@192.168.133.132
- expect {
- "yes/no" { send "yes\r"; exp_continue}
- "password:" { send "$passwd\r" }
- }
- expect "]\*" // 表示命令行前的部分, PS1 的最后部分 root 用户是]#, 普通用户是]$, 因此需要通配
- send "touch /tmp/12.txt\r"
- expect "]\*"
- send "echo 1212> /tmp/12.txt\r"
- expect "]\*"
- send "exit\r" // 退出
3. 传递参数
- #!/usr/bin/expect
- set user [lindex $argv 0] // 定义变量 user 值为参数 1
- set host [lindex $argv 1] // 参数 2
- set passwd "123456"
- set cm [lindex $argv 2] // 参数 3, 发送的多条命令用分号隔开, 命令执行时间不能太长, expect 会有超时时间, 默认 10s. 也可以自行设置: set timeout [number] 单位 s, 设定 - 1 表示不限时间
- spawn ssh $user@$host
- expect {
- "yes/no" { send "yes\r"}
- "password:" { send "$passwd\r" }
- }
- expect "]\*"
- send "$cm\r"
- expect "]\*"
- send "exit\r"
4. 自动同步文件
- #!/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 // 不加这个会登录后立即退出导致根本没同步
5. 指定 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
6. 构建文件分发系统
需求背景: 对于大公司而言, 肯定时不时会有网站或者配置文件更新, 而且使用的机器肯定也是好多台, 少则几台, 多则几十甚至上百台. 所以, 自动同步文件是至关重要的.
实现思路: 首先要有一台模板机器, 把要分发的文件准备好, 然后只要使用 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:///list.txt 里有文件的绝对路径列表
- expect {
- "yes/no" { send "yes\r"}
- "password:" { send "$passwd\r" }
- }
- expect eof
ip.list 内容
- 192.168.133.132
- 192.168.133.133
- ......
rsync.sh 内容
- #!/bin/bash
- for ip in `cat ip.list`
- do
- ? ? echo $ip
? ? ./rsync.expect $ip list.txt
done
7. 命令批量执行
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 ip.list`
- do
- ? ? echo $ip
- ? ? ./exe.expect $ip "w;free -m;ls /tmp"
- done
来源: http://www.bubuko.com/infodetail-2604257.html