Remember to use the Python script to modify the Hosts file, because the company server needs to change the IP address, the server is a Linux system, and the hosts file some resolution of the IP, manual one of the resolution is too troublesome, wrote this script. I thought it was very simple, but the process of writing is very difficult to write, but also tried the shell script, but it is not good to write. Then directly in Python to write, but also found some online tutorials, but there is no good solution to the problem. Let's put the script down and record it.
#!/usr/bin/python#coding:utf8import osimport sysimport rehostsfile= "/etc/hosts" # Hosts file absolute path ip_dict = {"1.1.1.1": "2.2.2.1", "1.1.1.2": "2.2.2.2", "1.1.1.3": "2.2.2.3"} # This is a custom dictionary form for:old_ip:new_ipip = [] #定一个空列表, to store the OLD_IP list line=[] # an empty list, To store a list of the contents of the modified Hosts file Fd = open (hostsfile). ReadLines () #打开文件 # Get a list of old_ip with a for loop for old_ Ip in ip_dict.keys (): ip.append (OLD_IP) #用for循环列出每一行 and matching old_ip Replace with re.sub () if matched to. and stored in line this list For line in fd: if line.strip () == ': #continue line.append (line) # #如果是空行也加入列表中 to ensure that the contents of the document are consistent with the original content else: h_ip = line.strip (). Split () [0] # #取得hosts文件中的ip地址 if h_ip&Nbsp;in ip: lin = re.sub (h_ip,ip_dict[h_ip],line) #如果匹配到就进行替换 print "The contents of the file modification are as follows:" print "%s --> %s" % (Line.strip ("\ n"), Lin) line.append (Lin) else: line.append (line) #最后得到Line列表 # to re-write the contents of the list to/etc/ Hosts file in Fc = open (Hostsfile, ' W ') Fc.writelines (line) Fc.close ()
This article from the "Linux Learning" blog, declined reprint!
Python script modifies Hosts file