Toggling a Network Adapter with Python 3

if you frequently have to toggle between two network adapters in Windows, it can become a hassle to keep opening the Control Panel widget, right-click, disable/enable adapter, etc. For example, you may want to turn off your wired connection and connect to wifi, then switch back to wired, etc.

With Python and this 'admin' library (also attached to this post for download), you can just place a shortcut on the desktop and double-click to enable/disable a particular adapter.

To make this work:

  • make sure you have Python installed (I have Python 3.6)
  • place the following code in a python file (i.e. toggleLan.py)
  • change the name of "strAdapterName" to match your ethernet adapter's name
  • in the same folder, place the admin.py file (remove the "_.txt" extension if you're downloading from here)

Then create a shortcut to the toggleLan file anywhere you like (on your desktop, maybe?). In my application, you still have to deal with a Windows security (UAC) dialog window, but it's still much faster than doing it the old way!

toggleLan.py:

#!/usr/bin/env python

import wmi
import admin

strAdapterName = "Intel Ethernet Connection I24-FM"

# I found the admin module here:
# https://stackoverflow.com/questions/19672352/how-to-run-python-script-with-elevated-privilege-on-windows
if not admin.isUserAdmin():
        admin.runAsAdmin()

# good info for dealing with Network Adapters on Windows
# https://msdn.microsoft.com/en-us/library/aa394216(v=vs.85).aspx

c=wmi.WMI()
o=c.query("select * from Win32_NetworkAdapter")

for conn in o :
    #print(conn.Caption + " - " + conn.Description)
    if conn.name == strAdapterName:
        if conn.NetEnabled:
            conn.Disable()
        else:
            conn.Enable()
Attachment
main.py_.txt (577 bytes)

Comments

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.