在工作过程中经常需要批量对多台机器进行操作,如果每台都手动操作那效率实在是太低了。这时就需要一种自动交互的方式对若干台机器进行批量处理,expect就扮演着这样一种角色。本文以批量修改密码为例浅谈expect的用法
。Expect需要Tcl编程语言的支持,首先需要确定机器安装有expect,tcl。
[root@rac1 scripts]# rpm -qa|grep tcl
tcl-8.4.13-4.el5
tclx-8.4.0-5.fc6
[root@rac1 scripts]# rpm -qa|grep expect
expectk-5.43.0-5.1
expect-devel-5.43.0-5.1
expect-5.43.0-5.1
以上显示说明该机器装有expect和tcl
以下是批量修改密码脚本
用whereis expect确定expect位置
[root@rac1 ~]# whereis expect
expect: /usr/bin/expect
#!/usr/bin/expect
#设置变量
set timeout 10
set USERNAME etnet
set PASSWORD 123456
#一个循环,说明对哪些机器进行操作
foreach host {
192.168.151.89
192.168.151.90
} {
spawn ssh
[root@rac1 scripts]# rpm -qa|grep tcl
tcl-8.4.13-4.el5
tclx-8.4.0-5.fc6
[root@rac1 scripts]# rpm -qa|grep expect
expectk-5.43.0-5.1
expect-devel-5.43.0-5.1
expect-5.43.0-5.1
以上显示说明该机器装有expect和tcl
以下是批量修改密码脚本
用whereis expect确定expect位置
[root@rac1 ~]# whereis expect
expect: /usr/bin/expect
#!/usr/bin/expect
#设置变量
set timeout 10
set USERNAME etnet
set PASSWORD 123456
#一个循环,说明对哪些机器进行操作
foreach host {
192.168.151.89
192.168.151.90
} {
spawn ssh
-l root ${host}
#ssh首次登陆的验证,exp_continue会继续执行下一循环
expect {
"no)?" {send "yes\r";exp_continue}
"password:" {send "123456\r"}
}
#每个expect捕获一个提示符,send发送一条命令,命令以\r结尾。
expect "]*"
send "passwd ${USERNAME}\r"
expect "password:"
send "${PASSWORD}\r"
expect "password:"
send "${PASSWORD}\r"
expect "]*"
send "exit\r"
}
#ssh首次登陆的验证,exp_continue会继续执行下一循环
expect {
"no)?" {send "yes\r";exp_continue}
"password:" {send "123456\r"}
}
#每个expect捕获一个提示符,send发送一条命令,命令以\r结尾。
expect "]*"
send "passwd ${USERNAME}\r"
expect "password:"
send "${PASSWORD}\r"
expect "password:"
send "${PASSWORD}\r"
expect "]*"
send "exit\r"
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/27181165/viewspace-775806/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/27181165/viewspace-775806/