expect :是基于tcl的相对简单的一个免费脚本编程工具语言

用于实现自动和交互式任务程序进行通信,无需人工干预。比如:ssh ftp等,这些程序正常情况下需要手工与它们进行交互,而是用expect就可以模拟人工交互的过程,实现自动和远端程序交互,从而达到自动化的目的。

支持:Unix、linux和Windows平台

1) expect程序工作流程:spawn启动进程àexpect期待关键字àsend向进程发送字符à退出结束

2) expect 软件安装:

配置yum,然后执行 yum install expect –y 即可安装expect软件

3) expect 语法 :命令 [选项] 参数

4) spawn

spawn :expect的初始命令,用于启动一个进程,之后所有expect操作都在这个进程中进行,如果没有spawn语句,整个expect就无法执行了。

spawn使用方法:spawn ssh sshusr@192.1.1.10

spawn 支持选项: -open 启动文件进程

1
2
-ignore    忽略某些信号

5) expect

expect 使用方法: expect 表达式 动作 表达式 动作。。。。。。。。。。

1
2
expect命令用于等候一个相匹配内容输出,匹配上就执行expect后面的命令。

6) exp_continue

exp_continue :使用条件比较苛刻,首先它要处于一个expect命令中,然后属于一种动作,没有exp_continue会依次向下匹配多个条件,添加

exp_continue后每次的匹配都是有第一个关键词开始。(参考下方实例)

7) send_user

send_user:用于把参数输出到标准输出中,默认send、exp_send命令都是将参数输出到程序中。

1
2
3
4
5
6
7
8
         send_user “please input passwd:”

这句就会在标准输出中打印please input passwd: 字符,类似于“echo”。



常用参数:-re 表示使用正则表达式的方式匹配,使用起来如下:

spawn ssh sshusr@$ip

expect {

“yes/no” { send “yes\r”; exp_continue }

“Password:” { send “$sshusrpasswd\r” }

}

expect “sshusr”

send “su - root\r”

8) expect 变量

expect中变量设置方法

set 变量名 变量值 #设置变量方法

puts $变量名 #读取变量方法

9) expect 关键字

expect中的特俗关键字用于匹配过程,代表某些特殊含义或状态,一般用于expect族命令中而不能在外面单独使用,也可以理解事件。

1
2
3
4
5
6
 使用类似于: expect eof {  }

9.1 eof

eof 关键字用于匹配结束符,比如文件的结束符、FTP传输停止等情况,这个关键字后跟上动作来做进一步的控制,特别是FTP交互操作

方面,eof作用很大。

Spawn ftp jorbabe@192.168.20.3

Expect {

“password:” { exp_sed “who Im I” }

1
2
eof { ftp connect close }

}

Interact { }

1
2
3
4
9.2            timeout

Timeout 是expect的重要变量,它是一个全局性的时间开关,超时参数(秒),匹配的超时时间。

实例:远程登录设备并输入密码用户名并修改密码等操作

#!/bin/sh

#username

user=‘sshusr’

user2=‘root’

#sshusr

newpasswd=‘1111’

#root

newpasswd2=‘2222’

#sshusrpasswd

#newpasswd

#sshusrpasswd=‘1111’

#EnterPasswd

sshusrpasswd=‘0000’

#rootpasswd

#newpasswd

#rootpasswd=‘2222’

#EnterPasswd

rootpasswd=‘0000’

count=0

rm /tmp/iomdeskscript/changePasswd/test/expect.log

for ip in cat /tmp/iomdeskscript/changePasswd/test/devlist.txt

1
2
do

expect << EOF

set time 5

log_file /tmp/iomdeskscript/changePasswd/test/expect.log

spawn ssh sshusr@$ip

expect {

“yes/no” { send “yes\r”; exp_continue }

“Password:” { send “$sshusrpasswd\r” }

}

expect “sshusr”

send “su - root\r”

expect “Pa”

send “$rootpasswd\r”

expect “*#”

send “passwd $user\r”

expect “New”

send “$newpasswd\r”

expect “Reenter”

send “$newpasswd\r”

send “passwd $user2\r”

expect “New”

send “$newpasswd2\r”

expect “Reenter”

send “$newpasswd2\r”

send “exit\r”

send “exit\r”

expect eof

EOF

count= expr $count + 1

1
2
done

success= grep -i "Password changed" /tmp/iomdeskscript/changePasswd/expect.log |wc -l

echo change $count dev ,success $success dev~~~