如何同时管理多台服务器的expect脚本实例教程



如何同时管理多台服务器的expect脚本实例教程。exploring expect书籍,简单学了下expect脚本语言,这个脚本语言是tcl语言的扩展,用来解决一些工具无法自动交互的问题,如ssh登录时,无法在命令就指定密码等。下面是利用expect来实现管理多台服务器的简单例子:

#!/usr/bin/expect
#purpose:auto run command on multiple servers
#how to: mms <user> <cmd>
#write by zhumaohai.
#blog:http://www.centos.bz/

if {$argc < 2} {
puts “usage: mms <user> <cmd>”
exit 1
}

#set servers
set SERVERS {“192.168.0.100″ “192.168.0.101″ “192.168.0.102″}

#set password
set PASSWORDS(user1) “passwd1″
set PASSWORDS(user2) “passwd2″

#get virables
set USER [lindex $argv 0]
set CMD [lrange $argv 1 end]

set passwd $PASSWORDS($USER)

foreach x $SERVERS {
eval spawn ssh -l $USER $x $CMD
expect {
“password” { send “$passwd\r” }
“yes/no” { send “yes\r”;exp_continue; }
}
expect eof
}
1、这里定义了三台服务器192.168.0.100 192.168.0.101 192.168.0.102,定义了用户user1的密码为passwd1,用户user2的密码为passwd2,假如脚本文件名为ms,用法为:
./ms 用户 命令
如./ms user1 date
2、在使用脚本时,请确认系统已经安装有expect命令,centos使用yum install expect安装,ubuntu使用apt-get install expect安装。