一个管理多台服务器的expect脚本
时间:2014-11-05 12:54 来源:linux.it.net.cn 作者:IT
为大家提供一例expect脚本,expect脚本语言是tcl语言的扩展,可用来解决一些工具无法自动交互的问题。
例如ssh登录时,无法在命令行指定密码等操作。
例子,使用expect管理多台服务器。
复制代码代码示例:
#!/usr/bin/expect
#purpose:auto run command on multiple servers
#how to: mms <user> <cmd>
#site: www.it.net.cn
#
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安装即可。
(责任编辑:IT)
为大家提供一例expect脚本,expect脚本语言是tcl语言的扩展,可用来解决一些工具无法自动交互的问题。
例子,使用expect管理多台服务器。
复制代码代码示例:
#!/usr/bin/expect
#purpose:auto run command on multiple servers #how to: mms <user> <cmd> #site: www.it.net.cn # 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 }
代码说明: |