How to switch the hosts file using python

It is often necessary to switch hosts when doing development or testing. If there are more hosts, it is a tedious task to open the hosts file frequently to add a comment (#) to the address, and then remove the comment.

Of course, SwitchHosts can help us solve this cumbersome thing conveniently.

https://github.com/oldj/SwitchHosts

But I still try to use python to write a small program to switch. It is very interesting to be demand-driven to solve daily problems.

If we have a group of hosts:

172.168.12.107 www.baidu.com
172.168.10.213 account.baidu.com
172.168.12.107 pan.baidu.com
172.168.12.107 passport.baidu.com
172.168.10.129 is.baidu.com
172.168.12.107 un.baidu.com

Think about a few points before writing code.

1、 The hosts file is generally placed in our C:\WINDOWS\system32\drivers\etc\ directory without extension. We can open it through Notepad. The os module of python can be used to open local files.

2、 The operation we have to do is also very simple, add comments (add # sign), remove comments (remove # sign). When I remove the comment, when I open the browser to visit www.baidu.com, I actually visit the local host, 172.168.12.107. When the comment is added, the real Baidu server is accessed.

3、 The operation we have to do is to determine whether the first character of each row of data has a # sign, if not, add it.

Open the python shell and practice adding "#"

 abc ='127.168.10.107 www.baidu.com'
 a = abc[0]if a !='#':
 nabc ='#'+abc
 print nabc
#127.168.10.107 www.baidu.com

Define the abc string, abc[0] means to take the first character of the string and determine whether it is the # sign, if not, add the # sign to the front of the abc string.

The complete code with comments is entered as follows:

# coding=utf-8import os

def add_jing():
 input =open(r'C:\WINDOWS\system32\drivers\etc\HOSTS','r')
 lines = input.readlines()
 input.close()

 output =open(r'C:\WINDOWS\system32\drivers\etc\HOSTS','w')for line in lines:if not line:break
 jing = line[0]if jing !='#':
  print line
  nf ='#'+ line
  output.write(nf)else:
  output.write(line)

  output.close()if __name__ =="__main__":add_jing()

The program first opens the HOST file in read (r) mode, and the readlines() method reads the content line by line. Then, close() closes the file.

The program then opens the HOST file by writing (w), and judges whether there is a # sign for each line of data obtained by readlines(), and if not, add it. And write to the HOST file through the write() method. Finally, close() closes the file.

Open the python shell and practice the "#" operation:

 abc ='#127.168.10.107 www.baidu.com'
 a = abc[0]if a =='#':
 nabc = abc.replace('#','')
 print nabc
127.168.10.107 www.baidu.com

Also take the first character of the string to judge, if it is the # sign, then use the replace() method to replace the # sign with an empty (")

Uncommented complete code:

def del_jing():
 input =open(r'C:\WINDOWS\system32\drivers\etc\HOSTS','r')
 lines = input.readlines()
 input.close()

 output =open(r'C:\WINDOWS\system32\drivers\etc\HOSTS','w')for line in lines:if not line:break
 jing = line[0]if jing =='#':
  print line
  nf = line.replace('#','')
  output.write(nf)else:
  output.write(line)

  output.close()if __name__ =="__main__":del_jing()

The way to run the two functions add_jing() and del_jing() is not flexible. Here is just to switch the hosts by modifying #, then you can also define an array of hosts and write it directly to the HOST file. by

Write different arrays to achieve the purpose of switching between different hosts.

# coding=utf-8import os

''' Intranet test environment'''
insides =['172.168.12.107 www.baidu.com','172.168.10.129 pan.baidu.com','172.168.12.107 un.baidu.com','172.168.12.107 passport.baidu.com']'''External network test environment'''
outsides =['172.16.12.223 www.baidu.com','172.16.10.223 pan.baidu.com','172.16.12.111 un.baidu.com','172.16.12.223 passport.baidu.com']

def inside_test():
 output =open(r'C:\pyse\HOSTS.txt','w')for insid in insides:
 print insid
 output.write(insid)
 output.write("\n")
 output.close()

def outside_test():
 output =open(r'C:\pyse\HOSTS.txt','w')for outsid in outsides:
 print outsid
 output.write(outsid)
 output.write("\n")
 output.close()if __name__ =="__main__":
 # inside_test()outside_test()

The above method will be simpler. Write the defined host array to the HOST file. Note: Each array element needs to be written with a carriage return and line feed—write("\n")

If you want to continue to increase the convenience of switching hosts, you can use wxPython to write a host configuration interface, then it is our SwitchHosts tool.

The above is the whole content of this article, I hope it will be helpful to everyone's study.

Recommended Posts

How to switch the hosts file using python
How to practice after the python file is written
How to write python configuration file
How to save the python program
How to view the python module
How to debug python program using repr
How to learn the Python time module
How to use the round function in python
How to use the zip function in Python
How to use the format function in python
How to enter python through the command line
How to install the downloaded module in python
Python how to move the code collectively right
How to deal with python file reading failure
How to understand the introduction of packages in Python
Using Python to analyze the Guangzhou real estate market
How to comment python code
How to learn python quickly
How to uninstall python plugin
How to understand python objects
How to use python tuples
How to find the area of a circle in python
Python| function using recursion to solve
python how to view webpage code
How to use python thread pool
How Python implements the mail function
How does python change the environment
Using Python to implement multiple clipboards
How to omit parentheses in Python
How to install Python 3.8 on CentOS 8
How to write classes in python
How to filter numbers in python
How to read Excel in Python
How to install Python on CentOS 8
How to solve python dict garbled
How to view errors in python
How to write return in python
How Python operates on file directories
How Python implements the timer function
How to understand variables in Python
How to clear variables in python
How to understand python object-oriented programming
How to use SQLite in Python
How to install JDK 13 in the Linux environment using compressed packages
A practical guide to Python file handling
Why doesn't Python support the switch statement?
How to verify successful installation of python
How to make a globe with Python
How to use and and or in Python
How to delete cache files in python
How does python improve the calculation speed
How to represent null values in python
How to save text files in python
Python string to judge the password strength
How to use PYTHON to crawl news articles
How to write win programs in python
How to run id function in python
How to custom catch errors in python
How to write try statement in python
How to define private attributes in Python
R&D: How To Install Python 3 on CentOS 7