10

I am trying to find out how I can list all of the available wireless networks in Python. I am using Windows 8.1.

Is there a built-in function I can call, or through a library?

Please kindly show me the code which prints the list.

Code
  • 157
  • 2
  • 3
  • 16

3 Answers3

20

You'll want the subprocess module and a windows command:

import subprocess
results = subprocess.check_output(["netsh", "wlan", "show", "network"])

A little extra to just get SSID's.

results = results.decode("ascii") # needed in python 3
results = results.replace("\r","")
ls = results.split("\n")
ls = ls[4:]
ssids = []
x = 0
while x < len(ls):
    if x % 5 == 0:
        ssids.append(ls[x])
    x += 1
print(ssids)

https://docs.python.org/2/library/subprocess.html

weirdev
  • 1,388
  • 8
  • 20
  • 1
    ["netsh", "wlan", "show", "all"] gives more information, including the Access Point MAC Adresses (BSSIDD), if anyone needs those. – LuWi Mar 23 '16 at 12:18
  • 1
    @LuWi i tryed with "all" but fails with: 'ascii' codec can't decode byte 0xc3 in position 5996: ordinal not in range(128) – rodrigorf Dec 30 '17 at 13:53
  • @rodrigorf You might try decoding the text as Unicode: results = results.decode("utf8") – weirdev Jan 07 '18 at 21:31
  • 1
    @weirdev i am getting this error FileNotFoundError: [Errno 2] No such file or directory: 'netsh': 'netsh', i am using linux – 3bu1 Jul 18 '18 at 10:53
  • @3bu1 This answer is specifically for windows, as that is what OP was asking about. For Linux, you can do a similar thing by calling subprocess.check_output() with the proper command for your distro to list networks. You will have to parse the output differently as it will not be formatted the same as the windows output. – weirdev Jul 29 '18 at 02:53
9

This is a question from the olden days, but even at the time the accepted answer could have been much more Pythonic - e.g.,

r = subprocess.run(["netsh", "wlan", "show", "network"], capture_output=True, text=True).stdout
ls = r.split("\n")
ssids = [k for k in ls if 'SSID' in k]

If you just want to SSID names in a list, change the ssids = line to

ssids = [v.strip() for k,v in (p.split(':') for p in ls if 'SSID' in p)]
GT.
  • 1,140
  • 13
  • 20
  • Works perfectly. However, Windows sometimes needs to be kicked to show SSID that was recently activated. Any idea how to do that? I am doing that manually by clicking on network icon on the Windows task bar. :-( – Sany Sep 24 '21 at 10:37
-3

c:\netsh

C:\netsh\wlan

c:\netsh\wlan)Show all

Farzad Vertigo
  • 2,458
  • 1
  • 29
  • 32