脚本中利用数组实现对机器的批量控制
工作中对线上多台服务器使用脚本控制,如执行一些命令等。如果在脚本中对每台服务器都使用一条命令(因为服务器的ip,用户名,密码等可能不同),那么脚本会变得非常臃肿,且添加或删除服务器不方便。
例如远程连接一台服务器,将本机的文件备到服务器上,通常使用命令:
sshpass -p PASSWORD scp -p PORT -r /date/mysql/* USER@IP:/backup/
如果需要备份到100台服务器上,需要写100个这样的语句。
这里总结了几种利用数组实现主机组的定义,在命令中引用数组来实现简洁操作。
方法1:
#!/bin/bash array=( passwd1 port1 user1 ip1 passwd2 port2 user2 ip2 passwd3 port3 user3 ip3 passwd4 port4 user4 ip4 passwd5 port5 user5 ip5 passwd6 port6 user6 ip6 ) for ((i=0;i<${#array[*]};i=i+4));do echo passwoed is ${array[i]},port is ${array[i+1]},user is ${array[i+2]},ip is ${array[i+3]} #sshpass -p ${array[i]} ssh -p${array[i+1]} ${array[i+2]}@${array[i+3]} "命令" done
数组array中的每一行定义一个主机,明了且方便,可以添加多台服务器,这个方法最好。
返回的结果如下:
passwoed is passwd1,port is port1,user is user1,ip is ip1 passwoed is passwd2,port is port2,user is user2,ip is ip2 passwoed is passwd3,port is port3,user is user3,ip is ip3 passwoed is passwd4,port is port4,user is user4,ip is ip4 passwoed is passwd5,port is port5,user is user5,ip is ip5 passwoed is passwd6,port is port6,user is user6,ip is ip6
方法2:
#!/bin/bash passwd=([0]=passwd1 [1]=passwd2 [2]=passwd3 [3]=passwd4) port=([0]=port1 [1]=port2 [2]=port3 [3]=port4) user=([0]=user1 [1]=user2 [2]=user3 [3]=user4) ip=([0]=ip1 [1]=ip2 [2]=ip3 [3]=ip4) for i in $(seq 0 3);do echo password is ${passwd[i]},port is ${port[i]},user is ${user[i]},IP IS ${ip[i]} #sshpass -p ${passwd[i]} ssh -p${port[i]} ${user[i]}@${ip[i]} "命令" done
这里定义了4个数组,分别管理密码,端口,用户和ip,可以达到目的,但不是很明了,添加或去掉服务器时要仔细。
返回结果如下:
password is passwd1,port is port1,user is user1,IP IS ip1 password is passwd2,port is port2,user is user2,IP IS ip2 password is passwd3,port is port3,user is user3,IP IS ip3 password is passwd4,port is port4,user is user4,IP IS ip4
方法3:
#!/bin/bash array1=(passwd1 port1 user1 ip1) array2=(passwd2 port2 user2 ip2) array3=(passwd3 port3 user3 ip3) for i in `seq 1 3`;do echo password is ${array$i[0]},port is ${array$i[1]},user is ${array$i[2]},ip is ${array$i[3]} #sshpass -p ${array$i[0]} ssh -p${array$i[1]} ${array$i[2]}@${array$i[3]} "命令" done
这里每个数组定义一个服务器,直观,明了。但在引用数组中的元素时出错,
报错信息如下:
line 6: ${array$i[0]},port: bad substitution
${array$i[0]}中不能引用$i,所以这种方法是错误的,不知道为什么数组中的元素名不能用变量表示,希望有知道的朋友讲解一下。