expect
expect 是一个免费的编程工具语言,对于交互的场合,实现自动和交互式任务进行通信,而无需人的干预。
expect 安装:yum install -y expect
expect 脚本定义:默认以“.expect” 为后缀。脚本语言在首行要指明语言工具:#!/usr/bin/expect
expect 由一系列expect-send对组成:expect等待输出中输出特定的字符,通常是一个提示符,然后send 发送特定的响应。
# 假如通过SSH登录远程主机后,拷贝文件,那么就需要expect进程等待拷贝完成。
set timeout 10 #第3种方法
spawn rsync -av $file [email?protected]$host:$file
#或是 expect eot
# 或是 interact
构建文件分发系统
- 目标是通过spawn远程登录服务器,执行rsync命令将本地文件推送到远程主机上。
- 通过本地shell调用expect脚本,传递远程主机和同步文件参数。
#同步脚本名为ryn.expect .本地shell调用。
# 1远程主机列表和同步文件列表。
cat ../ip.list
192.168.10.2
192.168.10.5
cat ../file.list
1.txt
2.txt
#本地shell脚本
cat ../rsync.sh
#!/bin/bash
for ip in `cat ip.list`
do
echo $ip
./ryn.expect $ip list.txt
done
# 本地expect同步脚本
cat ../ryn.expect
#!/usr/bin/expect
set host [lindex $rage 0]
set filelist [lindex $ragv 1]
set passwd "123!45"
spawn rsync -av --files-from=$filelist [email?protected]$host:/
expect{
"yes/no"{ send "yesr" }
"password" { send "$passwdr" }
}
expect eof