Using Python to write scripts to enable Internet proxy for IE, pythonie

Source: Internet
Author: User

Using Python to write scripts to enable Internet proxy for IE, pythonie

The previous network in the factory needs to set up a proxy server to switch to various environments, including but not limited to the development environment, QA, pre-launch, acceptance, production environment, stress testing, Demo ......』 You must set different proxy servers for the browser.

Although you have a combination of Firefox + Change Host + HostAdmin + Proxy Selector to easily switch Host and browser Proxy... Everyone is afraid of "』.

But I had to change the browser when I encountered some bugs in IE !! We also need to open a virtual machine to get Internet Explorer 6, Internet Explorer 8, 360, and sogou !!!

Some colleagues suggested creating a bat script to do this, but no one would do it ...... In addition, whether or not bat can be implemented is not required. The point is that we are not familiar with it.

For a C # Write A winform or console, the. NET framework is not required. It takes a lot of time for a virtual machine to install. NET framework4.0. "And different snapshots must be installed once ...』

The most important thing is not to write articles for a long time. I don't want to write C # related content in my blog. As a result, I wrote several lines of code in Python to demonstrate the benefits of "I am using Python.

The specific implementation steps are as follows:

Install pywin32 and WMI support. Token)

Start.

First, check the information and find that the proxy content of IE is stored in "HKEYCURRENTUSER \ Software \ Microsoft \ Windows \ CurrentVersion \ Internet Settings" in the registry, therefore, in theory, we only need to modify the relevant key values here to switch to the IE proxy.

Therefore, the first function is to modify the registry key value:

def changeIEProxy(keyName, keyValue):  pathInReg = 'Software\Microsoft\Windows\CurrentVersion\Internet Settings'  key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,pathInReg, 0, win32con.KEY_ALL_ACCESS)  win32api.RegSetValueEx(key, keyName, 0, win32con.REG_SZ, keyValue)  win32api.RegCloseKey(key)

Therefore, pywin32 is used in the code segment. Therefore, the import win32api and win32con must be used at the beginning of the file to introduce related classes.

Modifying the system registry functions is actually just a few lines... Of course, because our factory must access the Internet through the proxy server, I only use REG_SZ to modify the key value type of the system registry. In other cases, there will be REG_DWORD and so on.

Then we need a configuration file to save different configuration information for various scenarios, "QA, Development Environment". At this time, the configuration file I used is in the ini format, you can use the Python ConfigParser to parse the file format.

The common configuration file formats of the region.

Because I have never used configuration files in the ini format before, this time I just learned how to use Python.

The code for reading the ini configuration file is:

config = ConfigParser.ConfigParser()config.read('config.ini')if config.has_section(_section):  _ProxyServer = config.get(_section, 'ProxyServer')  _ProxyOverride = config.get(_section, 'ProxyOverride')

Similarly, because ConfigParser is used, you need to import ConfigParser at the beginning of the file.

Careful friends will notice that the variable _ section in this code is not actually defined, and the meaning of this variable is the "scenario" written by the front side 』, for example, _ section = 'dev' indicates the development environment, and _ section = 'qa 'indicates the qa environment. This time, since we are doing a program similar to exe, therefore, _ section needs to be passed in as a parameter when executing exe.

At this time, we need to use the Python sys module. Similarly, we need to import sys, and then pass the following in the program:

_section = sys.argv[1] if len(sys.argv) > 1 else 'dev'

To obtain the "scenario" parameter in this way, the code will become:

_section = sys.argv[1] if len(sys.argv) > 1 else 'dev'config = ConfigParser.ConfigParser()config.read('config.ini')if config.has_section(_section):  _ProxyServer = config.get(_section, 'ProxyServer')  _ProxyOverride = config.get(_section, 'ProxyOverride')

Since the ProxyServer and ProxyOverride in the configuration file have been read, writing to the registry can theoretically complete the great business of modifying the IE proxy configuration:

_section = sys.argv[1] if len(sys.argv) > 1 else 'dev'config = ConfigParser.ConfigParser()config.read('config.ini')if config.has_section(_section):  _ProxyServer = config.get(_section, 'ProxyServer')  _ProxyOverride = config.get(_section, 'ProxyOverride')  changeIEProxy('ProxyServer', _ProxyServer)  changeIEProxy('ProxyOverride', _ProxyOverride)

The previous sentence is "Theoretically", because although the Registry content has been modified, the IE browser does not actually take effect. To make the content take effect, you need to close it and re-open it.

In this case, we will use the WMI plug-in installed on the front, import wmi ctypes, and then:

def kill_ie():  c = wmi.WMI()  kernel32 = ctypes.windll.kernel32  for process in c.Win32_Process():    if process.Name=='iexplore.exe':      kernel32.TerminateProcess(kernel32.OpenProcess(1, 0, process.ProcessId), 0)

Of course, there is a problem with this code. I only disabled IE and didn't re-open it ...... This is because I am lazy. I can open IE manually...

To sum up:

The complete code is:

# Coding = utf-8import win32api, win32con, sys, ConfigParser, OS, wmi, ctypesdef kill_ie (): c = wmi. WMI () kernel32 = ctypes. windll. kernel32 for process in c. win32_Process (): if process.name={' I %e.exe ': kernel32.TerminateProcess (kernel32.OpenProcess (1, 0, process. processId), 0) def changeIEProxy (keyName, keyValue): pathInReg = 'Software \ Microsoft \ Windows \ CurrentVersion \ Internet settings' key = win32api. regOpenKey (win32con. HKEY_CURRENT_USER, pathInReg, 0, win32con. KEY_ALL_ACCESS) win32api. regSetValueEx (key, keyName, 0, win32con. REG_SZ, keyValue) win32api. regCloseKey (key) def check_config (): if not OS. path. isfile ('config. ini '): cfg = ConfigParser. configParser () # Development Environment cfg. add_section ('dev') cfg. set ('dev', 'proxyserver', '2017. 168.0.6: 3128 ') cfg. set ('dev', 'proxyoverride', 'localhost; 127.0.0.1 ') # pre-launch cfg. add_section ('prepare') cfg. set ('prepare', 'proxyserver', '2017. 168.0.6: 3128 ') cfg. set ('prepare', 'proxyoverride', 'localhost; 127.0.0.1; ') # online cfg. add_section ('Online ') cfg. set ('online', 'proxyserver', '2017. 168.0.6: 3128 ') cfg. set ('online', 'proxyoverride', 'localhost; 127.0.0.1 ') # QA cfg. add_section ('qa ') cfg. set ('qa ', 'proxyserver', '2017. 168.2.16: 3128 ') cfg. set ('qa ', 'proxyoverride', 'localhost; 127.0.0.1') cfg. write (open ('config. ini ', 'A') return False return Trueif _ name _ = "_ main _": _ section = sys. argv [1] if len (sys. argv)> 1 else 'dev' if check_config (): kill_ie () config = ConfigParser. configParser () config. read ('config. ini ') if config. has_section (_ section): _ ProxyServer = config. get (_ section, 'proxyserver') _ ProxyOverride = config. get (_ section, 'proxyoverride') changeIEProxy ('proxyserver', _ ProxyServer) changeIEProxy ('proxyoverride', _ ProxyOverride) print 'done, open ie 'else: print 'config. ini is created, modify config. ini and try again'

Related Article

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.