• Post author:
  • Post category:shell
  • Post comments:0评论

需求,需要按照给出 excel 表格来批量修改 IP 对应的主机名
以下是对应关系表,空格和制表符为分隔符都可以:

[root@cp3 ~]# cat ip_hostname.txt
10.88.88.11     cp1
10.88.88.12     cp2
10.88.88.13     cp3

脚本内容(没用ansible,用ssh也可)(将修改主机名命令直接放到while循环里面也可以,我这里只是想用用字典):

#!/bin/bash
while read line;do
  declare -A ip
  ipa=`echo $line | awk '{print $1}'`
  hostname=`echo $line | awk '{print $2}'`
  ip["$ipa"]="$hostname"
done < /root/ip_hostname.txt
for i in ${!ip[*]};do
  ansible $i -m shell -a "hostnamectl set-hostname ${ip[$i]}"
done

执行效果:

[root@cp3 ~]# bash update_hostname.sh 
10.88.88.11 | CHANGED | rc=0 >>

10.88.88.12 | CHANGED | rc=0 >>

10.88.88.13 | CHANGED | rc=0 >>

[root@cp3 ~]# ansible all -m shell -a "hostname"
10.88.88.11 | CHANGED | rc=0 >>
cp1
10.88.88.12 | CHANGED | rc=0 >>
cp2
10.88.88.13 | CHANGED | rc=0 >>
cp3

发表评论

验证码: 78 + = 88