expect 是由Don Libes基于Tcl( Tool Command Language )语言开发的,主要应用于自动化交互式操作的场景,借助Expect处理交互的命令,可以将交互过程如:ssh登录,ftp登录等写在一个脚本上,使之自动化完成。尤其适用于需要对多台服务器执行相同操作的环境中,可以大大提高系统管理人员的工作效率
示例1:ssh非交互登录
#!/usr/bin/expect
set ip [lindex $argv 0] #变量,传递位置参数
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh $user@$ip #spawn用来启动脚本和命令的会话,它用于启动一个进程,之后所有expect操作都在这个进程中进行。
expect {
"yes/no" { send "yes\r"; exp_continue }
"password:" { send "$password\r" };
} #逐行匹配,第1步不匹配继续匹配第2步
expect "]#"
send "useradd testuser1\r"
send "echo $password |passwd --stdin testuser1 &>/dev/null\r"
send "exit\n"
expect eof
#interact
语法解析:
参数
set ---设置变量
[lindex $argv 0] ---脚本位置传参
argv ---参数数组,下标从0开始
spawn ---派生交互程序
expect ---匹配交互程序特定的标准输出字符串
send ---- 匹配成功后,将特定字符串发送给交互程序
exp_continue ---匹配多个字符串在执行动作后加此命令
interact ---执行完成后保持交互状态,否则退出
expect eof ---退出spawn开启的进程
set timeout 设置超时时间
示例2:scp非交互传输文件
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set filename [lindex $argv 2]
set password xxxxxxxx
set timeout 5
spawn scp -r $filename $user@$ip:/tmp
expect {
"yes/no" {send "yes\r"; exp_continue}
"password:" {send "$password\r"};
}
expect eof
示例3:实现批量主机公钥推送
#!/usr/bin/bash
>ip.txt
rpm -q tcl &>/dev/null
if [ $? -ne 0 ];then
echo "安装tcl组件,请等待..."
yum -y install tcl &>/dev/null
if [ $? -eq 0 ];then
echo "tcl组件安装完成"
fi
fi
rpm -q expect &>/dev/null
if [ $? -ne 0 ];then
echo "安装expect,请等待..."
yum -y install expect &>/dev/null
if [ $? -eq 0 ];then
echo "expect安装完成"
fi
fi
if [ ! -f ~/.ssh/id_rsa];then
echo "正在生成证书,请稍等..."
ssh-keygen -P "" -f ~/.ssh/id_rsa
echo "证书已生成"
fi
#------------------------实现主要功能模块-------------------------------------------
for i in {2..140}
do
{
ip=192.168.40.$i
password=" xxxxxxx"
ping -c1 -W1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo "$ip" >> ip.txt
/usr/bin/expect <<-EOF
set timeout 10
spawn ssh-copy-id $ip
expect {
"yes/no" { send "yes\r"; exp_continue }
"password:" { send "$password\r" }
}
expect EOF
EOF
fi
}&
done
wait
echo "finish..."
#--------------------------------------------------------------------------------------