標籤:python 網路連接
#coding=GB2312import osimport sys import subprocessimport _winregLOCAL_CONNECT_NAME = '本地串連'WIFI_CONNECT_NAME = '無線網路串連'INTERNET_SETTING_REG = r'Software\Microsoft\Windows\CurrentVersion\Internet Settings'PROXY_ENABLE_NAME = 'ProxyEnable'def setEnable(connName, enable=True):str_enable = ''if enable:str_enable = 'enable'else:str_enable = 'disable'cmd='netsh int set int name=%s admin=%s' %('"'+connName+'"',str_enable)print cmdret =subprocess.call(cmd, shell=True)#print 'ret=',retif ret != 0:print '網路連接設定失敗'else:print '網路連接設定成功'def setIEProxyEnable(val= 1):try:#OpenKey預設以唯讀許可權開啟,由於沒有設定_winreg.KEY_ALL_ACCESS#導致後面的setValueEx掛掉,出現WindowsError [5]#要特別注意開啟許可權key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,INTERNET_SETTING_REG,0, _winreg.KEY_ALL_ACCESS)v, t = _winreg.QueryValueEx(key, PROXY_ENABLE_NAME)if v != val:_winreg.SetValueEx(key, PROXY_ENABLE_NAME, 0, t, val)except Exception,e:print '設定IE代理失敗:' , e.messagesys.exit(0)print '設定代理成功'if __name__ == '__main__':reload(sys)sys.setdefaultencoding('GB2312')setIEProxyEnable(0)if len(sys.argv) != 2:print 'switch_net.py N\r\n0:local 1:wifi.'sys.exit(0)if int(sys.argv[1]) == 0:setEnable(LOCAL_CONNECT_NAME)setEnable(WIFI_CONNECT_NAME,False)setIEProxyEnable()else:setEnable(LOCAL_CONNECT_NAME,False)setEnable(WIFI_CONNECT_NAME)setIEProxyEnable(0)
python切換網路連接