[Python / OSX]Get network connection details, restart wifi, and do more than you think straight from python

Hi!
I recently figured out how to restart internet(en0) interface on OSX and read some interesting details about our connection. Thanks to objc library I was able to access objective-C methods provided by OSX.
Here is CWInterface Class Reference. Check it out because this documentation provide many interesting methods.

I hope this code will help you guys 😀


#!/usr/bin/python
import objc, time
t=5
objc.loadBundle('CoreWLAN',
                bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
                module_globals=globals())

iface = CWInterface.interface()
print("Wifi is going to be powered off and on back again.")
while t > 0:
	print(t)
	time.sleep(1)
	t=t-1
iface.setPower_error_(False, None)
print("Wifi is off..\n")
time.sleep(5)
print("Wifi is on now..\n")
iface.setPower_error_(True, None)
time.sleep(6)
print("Back in service\n")
for iname in CWInterface.interfaceNames():
  interface = CWInterface.interfaceWithName_(iname)
  print """
Interface:      %s
SSID:           %s
Transmit Rate:  %s
Transmit Power: %s
RSSI:           %s""" % (iname, interface.ssid(), interface.transmitRate(),
                         interface.transmitPower(), interface.rssi())

Output:

Code output

Please share this if you find it helpful 🙂

Published by

@pawisoon

Programmer, designer and dubstep listener.