Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associating my Windows computer to a wifi AP with Python

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?

like image 525
Michael0x2a Avatar asked Dec 29 '12 01:12

Michael0x2a


2 Answers

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.

like image 177
Michael0x2a Avatar answered Nov 17 '22 05:11

Michael0x2a


The answer you linked talks about calling low level C functions from the Windows API. Fiddling with low level stuff makes my brain hurt.

There is a .Net wrapper around the native C calls, you can use this higher level API directly from IronPython. Unfortunately it is not well documented, but looking at the C# sample and digging over the sources should be easier than calling the underlying API. This is a very windows-centric solution, so you may be better served by powershell.

like image 27
Paulo Scardine Avatar answered Nov 17 '22 06:11

Paulo Scardine