用Python编写脚本使IE实现代理上网的教程
厂里上个网需要设置代理服务器,切换各种环境『包括但不仅限于开发环境、QA、预上线、验收、生产环境、压力测试、Demo……』都需要给浏览器设置不同的代理服务器。
虽然俺有神器Firefox+Change Host+HostAdmin+Proxy Selector的组合来轻松切换Host,切换浏览器代理,但是…凡是就怕『但是』。
但是碰到一些IE才有的bug时候不得不换浏览器啊!!还要开虚拟机进去搞IE6、IE8、360、搜狗这些奇葩浏览器啊!!!
有同事建议搞个bat脚本来做这些,但没人肯动手……而且bat能不能实现先不说,重点是咱不熟啊。
搞个C#写个winform或者console控制台还需要.NET framework不是,虚拟机装个.NET framework4.0又要很多时间『而且不同的snapshot都要装一遍…』
最最重要的,好久不写文章了不是,咱不想在博客里写C#相关的东西不是。所以,操刀Python写几行代码和厂里兄弟们显摆一下『人生苦短,我用Python』的好处。
具体实现步骤如下:
安装pywin32、WMI支持。具体下载地址Google一下,因为我的是32位python2.7系列,下载到的文件名分别为(pywin32-218.win32-py2.7.exe、WMI-1.4.7.win32.exe)
开搞。
首先,我们查资料知道,IE浏览器的代理内容在注册表中『HKEYCURRENTUSER\Software\Microsoft\Windows\CurrentVersion\Internet Settings』这里存着,所以我们理论上只要修改这里相关的键值就可以切换IE代理。
所以,第一个函数就是修改注册表键值:
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)
因此段代码中用到了pywin32的的东西,所以在文件最开头需要做import win32api, win32con,引入相关的class
修改系统注册表的函数其实就这么几行…当然,因为我厂必须通过代理服务器上网,所以修改系统注册表的键值类型我只用到了REG_SZ这一种,实际其他情况还会有REG_DWORD啊等等类型。
然后咱需要一个配置文件,来保存各种场景『QA啊开发环境啊』的不同的配置信息,这时候我使用的配置文件为ini格式,用Python自带的ConfigParser就可以解析此种文件格式。
没有采用以往我最熟悉的XML或者json纯粹为了装x,xml和json总觉着是web上用的东西,ini看起来比较像一个.exe比较常用的配置文件格式。
也因为以前没用过ini格式的配置文件,这次权当又学会一种Python的玩法而已。
所以读取ini配置文件的代码为:
config = ConfigParser.ConfigParser() config.read('config.ini') if config.has_section(_section): _ProxyServer = config.get(_section, 'ProxyServer') _ProxyOverride = config.get(_section, 'ProxyOverride')
同样,因为用到了ConfigParser,需要在文件最开头也import ConfigParser一下。
细心的小伙伴会注意到这段代码中有一个_section的变量实际是没有定义的,而这个变量俺给它的含义是前边所写的『场景』,比如_section=='dev'表示开发环境,_section=='qa'表示QA环境,而咱们这次既然做的是一个类似exe的程序,所以_section需要在执行exe时候当作参数传进来。
这时候咱们就要用到Python的sys模块了,同样import sys,然后在程序中通过:
_section = sys.argv[1] if len(sys.argv) > 1 else 'dev'
这样的方式来获取『场景』这个参数,这一段代码就会变成:
_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')
既然已经读取到配置文件中的ProxyServer和ProxyOverride这俩东东了,写入到注册表理论上就能完成咱们的修改IE代理配置的大业了:
_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)
前一句为啥是『理论上』呢,因为注册表内容虽然已经修改了,但实际上IE浏览器并没有生效,让IE浏览器生效需要关闭重新打开。
这时候就用到前边安装的一个叫做WMI的东东,import wmi ctypes,然后:
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)
当然,这段代码是有一点点问题的,只关闭了IE没有重新打开……是因为俺偷懒了,俺可以接受手动打开IE…
综上所述:
完整的代码为:
#coding=utf-8 import win32api, win32con, sys, ConfigParser, os, wmi, ctypes 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) 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() #开发环境 cfg.add_section('dev') cfg.set('dev', 'ProxyServer', '192.168.0.6:3128') cfg.set('dev', 'ProxyOverride', 'localhost;127.0.0.1') #预上线 cfg.add_section('prepare') cfg.set('prepare', 'ProxyServer', '192.168.0.6:3128') cfg.set('prepare', 'ProxyOverride', 'localhost;127.0.0.1;') #线上 cfg.add_section('online') cfg.set('online', 'ProxyServer', '192.168.0.6:3128') cfg.set('online', 'ProxyOverride', 'localhost;127.0.0.1') #QA cfg.add_section('qa') cfg.set('qa', 'ProxyServer', '192.168.2.16:3128') cfg.set('qa', 'ProxyOverride', 'localhost;127.0.0.1') cfg.write(open('config.ini', 'a')) return False return True if __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'

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
