Associating my Windows computer to a wifi AP with Python

不羁的心 提交于 2019-12-29 06:57:19

问题


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?


回答1:


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.




回答2:


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.




回答3:


I've written a Python CLI tool for controlling Wi-Fi over command line interface. There's a library in this project, and it should fit your requirement.

https://github.com/changyuheng/pywinwifi

There's another standalone library but I've never tried it.

https://github.com/reedcourty/pynetsh



来源:https://stackoverflow.com/questions/14077835/associating-my-windows-computer-to-a-wifi-ap-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!