同时管理多台服务器的expect脚本

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

  1. #!/usr/bin/expect
  2. #purpose:auto run command on multiple servers
  3. #how to:  mms <user> <cmd>
  4. #write by zhumaohai.
  5. #blog:https://www.centos.bz/
  6.  
  7. if {$argc < 2} {
  8. puts "usage: mms <user> <cmd>"
  9. exit 1
  10. }
  11.  
  12. #set servers
  13. set SERVERS {"192.168.0.100" "192.168.0.101" "192.168.0.102"}
  14.  
  15. #set password
  16. set PASSWORDS(user1) "passwd1"
  17. set PASSWORDS(user2) "passwd2"
  18.  
  19. #get virables
  20. set USER [lindex $argv 0]
  21. set CMD [lrange $argv 1 end]
  22.  
  23. set passwd $PASSWORDS($USER)
  24.  
  25. foreach x $SERVERS {
  26. eval spawn ssh -l $USER $x $CMD
  27. expect {
  28. "password" { send "$passwd\r" }
  29. "yes/no" { send "yes\r";exp_continue; }
  30. }
  31. expect eof
  32. }

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安装。

发布于:2019-11-22 11:06:20