現在的服務器維護,大部分是用CMDB操作了,在使用CMDB批量改名的過程中,需要找到對應服務器的ip和相對應的hostname,然後進行hostname設置,以下是我經常使用的一個小腳本:
#!/usr/bin/env python
#-*- codinig: UTF-8 -*-
import os
import subprocess
import socket
ips = '''
10.0.0.1
10.0.0.2
'''
names = '''
test_server_01
test_server_02
'''
iplist = ips.split()
namelist = names.split()
ip_name = dict(zip(iplist, namelist))
#獲取服務器的lan ip,根據ip來匹配是否在需要改名的列表中
lanip = os.popen("ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}' | head -1").read().strip()
if lanip in ips:
#根據ip來獲取對應的hostname
hostname = ip_name[lanip]
#臨時性改名
subprocess.call(["hostname %s" %hostname], shell=True)
#永久改名,重啓生效
subprocess.call(["sed -i '/HOSTNAME/s/.*/HOSTNAME=%s/' /etc/sysconfig/network" %hostname], shell=True)
else:
print ("%s is not in change_list") %lanip
print('check hostname:')
print(lanip)
subprocess.call(["hostname"], shell=True)
subprocess.call(["cat /etc/sysconfig/network |grep 'HOSTNAME'"], shell=True)