Search code examples
pythonwindowscmdwifinetsh

Python list of lists from CMD output


Trying to parse the values of SSID, BSSID and Signal from CMD output by using python. The thing that confuses me is how to get those three values each time to store it in a list of lists. I could do it for every single line like so..

import subprocess, re

cmd = subprocess.Popen('netsh wlan show networks mode=BSSID',
shell=True, stdout=subprocess.PIPE) 
for line in cmd.stdout:
    if "BSSID" in line:
        print re.search(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', line, re.I).group()

But the problem is that i can understand it's not a good practice. What i am trying to achive is to have SSID, BSSID and Signal in lists so i can print any information from within the list. For example, print the BSSID of the second access point from my list, or for AP in APS: print SSID.

Any help would be appreciated!


Solution

  • Here is how you could parse the output into a list of dictionaries:

    import subprocess
    
    ssid = {}
    ssids = []
    cmd = subprocess.Popen('netsh wlan show networks mode=BSSID',
                           shell=True, stdout=subprocess.PIPE) 
    for line in cmd.stdout:
        l = map(lambda x: x.strip(), line.strip().split(":"))
        if len(l) > 1:
            key, value = l[0], l[1]
            if key.startswith("SSID"):
                key = "name"
                if ssid:
                    ssids.append(ssid)
                ssid = {}
                ssid[key] = value
            if "name" in ssid:
                ssid[key] = value
    ssids.append(ssid)
    
    # example of how to use ssids, list of ssid dictionaries
    for ssid in ssids:
        print ssid["name"], ssid["Encryption"]