Search code examples
pythonmacoswifipyobjc

How to connect to a Wi-Fi network using Python on OS X?


I want to connect to a Wi-Fi network using Python on OS X (10.11). Based on CWInterface reference I figured out there is a iface.associateToNetwork_password_error_() method available, however when called it does not connect to the network nor it does cause any exception.

At the same time iface.disassociate() works correctly and disconnects WiFi.

This is the code I tried:

import objc

objc.loadBundle('CoreWLAN',
       bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
       module_globals=globals())

iface = CWInterface.interface()

iface.associateToNetwork_password_error_(SSID, PASSWORD, None)

How can I connect to a specified network from Python on OS X and make sure the connection has been established?


Solution

  • I was able to successfully connect to my home network with the following:

    import objc
    
    objc.loadBundle('CoreWLAN',
                    bundle_path = '/System/Library/Frameworks/CoreWLAN.framework',
                    module_globals = globals())
    
    iface = CWInterface.interface()
    
    networks, error = iface.scanForNetworksWithName_error_('<Name Of Network>', None)
    
    network = networks.anyObject()
    
    success, error = iface.associateToNetwork_password_error_(network, '<Password Of Network>', None)
    

    Two key things that I suspect you were missing:

    1. You weren't passing in a CWNetwork as your first parameter.
    2. You weren't checking return values (IE, success and error in the final call). They could have helped you with tracking down any other issues, perhaps.