Expect简介
Expect是一个用来实现自动交互功能的软件套 件(Expect [is a] software suite for automating interactive tools)。使用它系统管理 员的可以创建脚本用来实现对命令或程序提供输入,而这些命令和程序是期望从终端(terminal)得到输入,一般来说这些输入都需要手工输入进行的。
1、依赖环境
expect依赖于tcl,但linux系统里一般不自带安装tcl,需要手动安装。
对于tcl的检测系统是否已经安装
rpm -qa | grep tcl
如果结果显示: tcl-8.4.13-4.el5
结果表示已经安装了 tcl 但是没有安装tcl-devel 所以就要安装,之前没有查看操作系统位数,下了64位的tcl-devel包,安装错误
2、expect 和tcl下载以及安装
expect版本 5.43下载路径:
http://download.chinaunix.net/download/0003000/2845.shtml
tcl版本 8.4.19下载:
Download Tcl from SourceForge.net
下载完后,分别解压安装
(1)、先安装tcl
进入tcl解压目录,然后进入unix目录
#./configure
#make
#make install
(2)、后安装expect
进入expect解压目录
#./configure --with-tclinclude=/usr/src/tcl8.4.19/generic/ --with-tclconfig=/usr/local/lib/
#make
#make install
完成,测试
#expect
exit 退出
执行远程登录
expect 执行脚本(expect -f)
免密码登录远程主机
执行脚本 expect –f test.exp
免密码登录远程主机执行命令并退出
-bash-4.1$ cat test2.exp
#!/usr/bin/expect -f
set ipaddr "10.255.254.48"
set passwd "echnweb"
spawn ssh echnweb@$ipaddr
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
expect "]# "
send "df\r"
send "exit\r"
expect eof
exit
执行:expect –f test2.exp
bash解析expect脚本
-bash-4.1$ cat test.sh
#!/bin/bash
ip1="10.255.254.48"
command1="ssh -l web -p 22 $ip1"
expect -c"
spawn $command1;
expect {
"10.255.254.48's
password:\" {send \"web\r\"; exp continue)}
\"web@\" {send \"df -h\r exit\r\";
exp_continue}
}
执行:sh test.sh
实战案例解析
案例1、登录通用登录脚本
通用脚本内容:
#!/usr/bin/expect -f
set ip [lindex $argv 0 ]
set username [lindex $argv 1 ]
set passwd [lindex $argv 2 ]
set command [lindex $argv 3]
set timeout 1
spawn ssh $username@$ip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$passwd\r" }
}
expect "*$*" { send "$command\r" }
expect eof
脚本内容介绍:set timeout 1 设置超时时间 1秒
set ip [lindex $argv 0 ] 接收传入参数格式(0 是接收第一个参数)
2、批量修改密码
#!/usr/bin/expect
set timeout 10
set USERNAME web
set PASSWORD 密码
foreach host {
10.255.201.19
10.255.201.19
10.255.201.19
10.255.201.19
10.255.201.20
10.255.201.21
10.255.201.22
10.255.201.23
10.255.201.24
10.255.201.25
10.255.201.26
10.255.201.27
10.255.201.28
10.255.201.29
} {
spawn ssh -l ${USERNAME} ${host}
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" {send "${USERNAME}\r"}
}
expect "]$"
#send "passwd ${USERNAME}\r"
send "passwd\r"
expect "password:"
send "${USERNAME}\r"
expect "new"
send "${PASSWORD}\r"
expect "new"
send "${PASSWORD}\r"
expect "]$"
send "exit\r"
}