Associating my Windows computer to a wifi AP with Python

Michael0x2a picture Michael0x2a · Dec 29, 2012 · Viewed 7.5k times · Source

I'm trying to write a python script that can make my computer associate to a wireless access point, given the name as a string. For example, I might specify I want to connect to linksys, and my script would cause the computer to do that.

I looked at this question, but wasn't able to understand what to do from looking at the links provided.

Can somebody point me in the right direction?

Answer

Michael0x2a picture Michael0x2a · Dec 29, 2012

I decided to take Paulo's suggestion and try using Powershell/the command line. I found an article about connecting to a network via the command line.

From the command line, you can do:

netsh wlan connect <profile-name> [name=<ssid-name>]

...where the name=<ssid-name> part is optional and is necessarily only if the profile contains multiple ssids.

However, it looks like the profile must already exist on the machine in order for the command line stuff to work. I did find a forum post on programatically creating a profile, but I didn't feel like canvassing through it.

If the profile name already exists, then from Python you can do something similar to the following:

import subprocess

def connect_to_network(name):
    process = subprocess.Popen(
        'netsh wlan connect {0}'.format(name),
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()

    # Return `True` if we were able to successfully connect
    return 'Connection request was completed successfully' in stdout        

It's an imperfect solution, and I'm not entirely sure if it'll work in every case, but it did work for my particular case. I thought I'd post what I came up with in case somebody else wants to try modifying it to make it better.