python自动代理切换

发布时间:2019-09-18 07:24:51编辑:auto阅读(2588)

     

    1. import socket 
    2. import os 
    3. import time 
    4. import winreg 
    5. import wmi 
    6.  
    7. '''''set/unset proxy, according to ip addr''' 
    8. def proxy(enable): 
    9.     root = winreg.HKEY_CURRENT_USER 
    10.     subkey = r'Software\Microsoft\Windows\CurrentVersion\Internet Settings' 
    11.     valuename = 'ProxyEnable' 
    12.     key = winreg.OpenKey(root, subkey, access=winreg.KEY_ALL_ACCESS) 
    13.     value, t = winreg.QueryValueEx(key, valuename) 
    14.     #print(value, t) 
    15.     if enable: 
    16.         if value == 1: 
    17.             print('Already enable proxy!') 
    18.             return 0 
    19.         winreg.SetValueEx(key, valuename, 0, t, 1) 
    20.         killie() 
    21.         print('Enable proxy Done!') 
    22.     else: 
    23.         if value == 0: 
    24.             print('Already unable proxy!') 
    25.             return 0 
    26.         winreg.SetValueEx(key, valuename, 0, t, 0) 
    27.         killie() 
    28.         print('Disable proxy Done') 
    29.  
    30. def unproxy(): 
    31.     proxy(False) 
    32.  
    33. def killie(): 
    34. ''' if ie running, kill it. make change takes effect'''
    35.     c = wmi.WMI(find_classes=False) # turn off introspection 
    36.     for p in c.Win32_Process(['Name']): 
    37.         if p.Name == 'iexplore.exe': 
    38.             os.system('taskkill /im iexplore.exe /f') 
    39.             return 
    40.     print('Not found iexplore.exe!')     
    41.      
    42.  
    43. def getipaddr(): 
    44.     '''first get all interface addr''' 
    45.     #hostname = socket.getfqdn(socket.gethostname()) 
    46.     hostname = socket.gethostname() 
    47.     hostaliasip = socket.gethostbyname_ex(hostname) 
    48.     #host, hostalias, iplist = hostaliasip 
    49.     return hostaliasip 
    50.  
    51. def main(iplist): 
    52.     '''''check whether at room, if true, cancel proxy''' 
    53.     network = '192.168.1.' 
    54.     for ip in iplist: 
    55.         if network in ip: 
    56.             unproxy() 
    57.             return 0 
    58.     # else enable proxy 
    59.     proxy(True) 
    60.  
    61. if __name__ == '__main__': 
    62.     main(getipaddr()[2]) 
    63.     time.sleep(2) 

     

关键字:

上一篇: 用python写的agent

下一篇: Python -- abc module