python修改linux主机ip
修改虚拟机的主机ip 和hostname
1 import os, sys 2 3 4 def conf_ip(ip): 5 iplist = [] 6 f = open("/etc/sysconfig/network-scripts/ifcfg-eth0", "r+") 7 for i in f: 8 iplist.append('BOOTPROTO="static"\n' if 'BOOTPROTO=' in i else i) 9 iplist.extend(['IPADDR="192.168.1.{0}"\n'.format(ip),'NETMASK="255.255.255.0"\n','GATEWAY="192.168.1.254"\n']) 10 f.seek(0,0) 11 f.writelines(iplist) 12 f.truncate() 13 f.close() 14 15 16 def set_hostname(host): 17 with open("/etc/hostname", "w") as f: 18 f.write(host) 19 20 21 if __name__ == '__main__': 22 if len(sys.argv) == 3 and sys.argv[1].isdigit(): 23 conf_ip(sys.argv[1]) 24 set_hostname(sys.argv[2]) 25 os.remove(sys.argv[0])