Python script modifies Hosts file

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.