windown 使用python 自动切换网络
由于工作环境的特殊性,有时需要切换到内网工作,有时需要通过手机连接外网,想自动运行一个脚本就做完这事
首先在PC机上安装一个无线网卡,例如360wifi就可以。
除了python,还用到了DOS命令,事实我觉得可以直接通过python来实现,有时间再试试。
以下是实现代码:
import os import time import sys import socket import subprocess NET_WLAN_NAME = "WLAN" NET_LOCAL_NAME = "本地连接" def operate_network_adapter(adaptername, toopen): processx = None try: cmd = "netsh interface set interface \"%s\" admin=%s" %(adaptername, "disabled" if toopen==False else "enabled") processx = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, creationflags=0x08000000) processx.wait() if processx.returncode == 0: print('\n cmd \"%s\" success.\n' %cmd) else: print('\n cmd \"%s\" error.\n' %cmd) processx.kill() pass except: print('\n%s\n' %(sys.exc_info()[1])) pass finally: if processx != None: processx.kill() pass pass if __name__ == "__main__": process = None try: myname = socket.getfqdn(socket.gethostname()) myaddr = socket.gethostbyname(myname) if '127.0.0.1' not in myaddr: #open local network operate_network_adapter(NET_WLAN_NAME, False) time.sleep(2) operate_network_adapter(NET_LOCAL_NAME, True) else: #open wlan operate_network_adapter(NET_LOCAL_NAME, False) time.sleep(2) operate_network_adapter(NET_WLAN_NAME, True) pass except: print('\n%s\n' %(sys.exc_info()[1])) pass finally: pass
作者:SCPlatform
Email:SCPlatform@outlook.com
本文旨在学习、交流使用,任何对文章内容的出版、印刷,对文章中提到的技术的商业使用时,请注意可能存在的法律风险。