Python list of lists from CMD output

791 views Asked by At

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!

2

There are 2 answers

0
Thibaut On BEST ANSWER

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"]
0
mrkbutty On

Also in your original code you are using .group() which will return the whole matched part of the line.

You can use group() with a positional parameter to get that group from the reg ex. e.g. group(2) would return the second item from your regex, ([0-9A-F]{2}).

To return a tuple of items you could append to an list just use groups().

For example assuming your regex is correct change this part;

mylist=list() 
for line in cmd.stdout:
    if "BSSID" in line:
       mylist.append(re.search(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', line, re.I).groups())

After the above mylist will contain a list of tuples with your extracts from each line.