CMDB批量操作給Linux服務器改hostname

現在的服務器維護,大部分是用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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章