Skip to content

Instantly share code, notes, and snippets.

@gufengxiaoyuehan
Created June 27, 2019 07:25
Show Gist options
  • Save gufengxiaoyuehan/aa75d885009e3c285135e1fb8343cb5e to your computer and use it in GitHub Desktop.
Save gufengxiaoyuehan/aa75d885009e3c285135e1fb8343cb5e to your computer and use it in GitHub Desktop.
windows system switch interface need run as administrator and change the interace name in line:30-39
import locale
import subprocess
from argparse import ArgumentParser
from collections import namedtuple
Interface = namedtuple("Interface", "admin_status status type name")
p = subprocess.run("netsh interface show interface", stdout=subprocess.PIPE)
interfaces = [Interface(*line.split()) for i, line in enumerate(p.stdout.decode(locale.getpreferredencoding()).replace("\r", "").split("\n"))
if i > 2 and len(line.split()) == 4
]
print(f"interfaces: {interfaces}")
def switch_status(interface, status):
"""
enable interface use netsh check return code and stdout if you
want sure it run correctly
:param interface:
:param status:
:return:
"""
cmd = f'netsh interface set interface name="{interface}" admin={status}'
print(cmd)
p = subprocess.run(cmd, shell=True)
print(p.returncode, p.stdout and p.stdout.decode(locale.getpreferredencoding()) or None )
def enable_wifi():
switch_status("WLAN", "enable")
switch_status("以太网", "disable")
def enable_enth():
switch_status("WLAN", "disable")
switch_status("以太网", "enable")
if __name__ == '__main__':
arg_parser = ArgumentParser("switch between wifi and enthnet")
# only one can input
exclude_group = arg_parser.add_mutually_exclusive_group()
exclude_group.add_argument("-w", "--wifi", action="store_true", help="enable wifi and disable enthnet",)
exclude_group.add_argument("-e", "--enthnet", action="store_true", help="enable enthnet and disable wifi")
args = vars(arg_parser.parse_args())
if args.get("wifi") or not args.get("wifi") and not args.get("enthnet"):
print("enable wifi")
enable_wifi()
elif args.get("enthnet"):
print("enable enthnet")
enable_enth()
else:
arg_parser.print_help()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment