2015年(68)
分类: 系统运维
2015-08-31 19:05:03
由于工作关系,经常要对远程的多台linux服务器进行远程维护,如拷贝一些更新脚本到远程进行更新等,由于所有的服务器都有一个相同的用户名及密码(有没安全隐患暂且不管,如果没有相同的用户及密码可先用ssh生成密钥对)。为了方便,写了以下脚本。此脚本较具灵活性,略做修正就能用作他用,如批量修改远程服务器的用户密码、批量在远程服务器执行同一命令(如重启所有服务器等)等。
#!/usr/bin/expect -f
##
##----------------------------------------------------------
## 文件名: rscp.exp
## 用 途: 批量的拷贝文件到多台远程主机
## 用 法: 脚本名 主机表 待拷贝的文件名 密码
## 日 期:2008-1-15
## 版 本: v1.0
##-----------------------------------------------------------
proc warning {argc hosts file} { if {$argc<3} {
send_user "usage: command hosts file password\n"
exit
} elseif {[file isfile $hosts]!=1} {
send_user "Sorry: File $hosts not found!\n"
exit
} elseif {[file isfile $file]!=1} {
send_user "Sorry: File $file not fonud!\n"
exit
}
}
proc login {password failed IP} {
set done 1
set timeout 30
while {$done} {
expect -re "Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"
} -re "password:" {
send "$password\r"
} -re "Permission denied, please try again." {
puts $failed $IP
break
} -re "kB/s|MB/s" {
set timeout -1
} -re "file list ..." {
set timeout -1
} -re "bind: Address already in use" {
set timeout -1
} -re "Is a directory|No such file or directory" {
puts $failed $IP
break
} -re "Connection refused" {
puts $failed $IP
break
} -re "No route to host" {
puts $failed $IP
break
} -re "cannot create regular file" {
send_user "\n"
send_user " #------------------------------------#\n"
send_user " # Copy complete! #\n"
send_user " # Please read the file copy-failed #\n"
send_user " #------------------------------------#\n"
send_user "\n"
exit
} timeout {
puts $failed $IP
break
} eof {
break
}
}
}
#设置运行参数
set argc $argc
set hosts [lindex $argv 0]
set file [lindex $argv 1]
set password [lindex $argv 2]
warning $argc $hosts $file
set failed [open copy-failed w+]
set f [open $hosts r]
#设置远程目录
set directory {/tmp}
#执行命令
while {[gets $f IP]} {
set cmd "scp $file $IP:$directory"
eval spawn $cmd
login $password $failed $IP
}
close $f