Expect是基于Tcl的相对简单的一个免费的基本变成工具语言,用于实现自动和交互式任务程序进行通信,无须人工干预。
1、Expect的安装
[root@C58-Server]# rpm -qa expect expect-5.43.0-8.el5 expect-5.43.0-8.el5 #如果未安装expect,可以通过yum进行安装 [root@C58-Server]# yum install expect -y
2、Linux的系统版本和内核版本
[root@C58-Server]# cat /etc/redhat-release CentOS release 5.8 (Final) [root@C58-Server]# uname -a Linux C58-Server 2.6.18-308.el5 #1 SMP Tue Feb 21 20:06:06 EST 2012 x86_64 x86_64 x86_64 GNU/Linux
Expect程序工作流程:spawn启动进程 ——> expect期待关键字 ——> send向进程发送字符 ——> eof退出结束
#!/usr/bin/expect
if { $argc != 3 } #获取参数的个数
{
send_user "usage:expect scp-expect.exp file host dir\n"
exit
}
#定义变量
set file [lindex $argv 0]
set host [lindex $argv 1]
set dir [lindex $argv 2]
set password "nowsun.net" #对变量password进行赋值
spawn scp -P 22 -p $file root@$host:$dir #启动scp的拷贝进程
expect {
#获取yes/no的关键字,如果获取到,则自动填写yes
#/r为在send中识别为回车,/n识别为换行,/t识别为制表符
"yes/no" {send "yes\r";exp_continue}
"password" {send "$password\r";exp_continue}
eof
}
exit -onexit { #退出脚本之前做一些扫尾工作,可以接一些命令。
send_user "Good bye\n"
}
#如果不想退出该进程可以使用interact
#spawn ssh ip,这样ssh到远程服务器的时候就不会自动退出来。说明:
send_user命令用来把后面的参数输出到标准输出中去,即显示到屏幕上
send、exp_send命令都是将参数输出到程序中去
exp_continue属于一个动作命令,命令可以不断循环匹配,输入多条命令。
说如果没有这个命令,匹配第一个关键字以后就会继续匹配第二个关键字,但
有了这个命令后,匹配第一个关键字以后,第二次匹配仍然从第一个关键字开始。
exit命令功能很简单,就是直接退出脚本。
eof(end-of-file)关键字用于匹配结束符。
#!/bin/sh
. /etc/init.d/functions #调用functions函数供/bin/true和/bin/false使用
for ip in {10.0.0.10,10.0.0.12}
do ping -c 2 $ip > /dev/null 2>&1
#[ $? -eq 0 ]用于判断ping -c 2 $ip执行的正确与否,不正确则为不为0,正确的话,则为0
if [ $? -eq 0 ];then
#引用copyfile.exp文件
expect copyfile.exp /etc/hosts $ip /tmp > /dev/null 2>&1
action "$ip" /bin/true
else
action "$ip" /bin/false
fi
done三、执行验证
[root@C58-Server]# sh copyfile.sh #因为10.0.0.12的主机不存在,所以执行的时候为失败 10.0.0.10 [ OK ] 10.0.0.12 [FAILED] #检查hosts文件是否拷贝成功 [root@C58-10-Client tmp]# ll total 8 -rw-r--r-- 1 root root 207 Dec 23 00:25 hosts
【CentOS】一个简单的Expect实例详解,布布扣,bubuko.com
原文:http://nowsun.blog.51cto.com/522159/1427304