Search code examples
pythonparsingwifi

python parsing wifi SSID data


I currently have the following. But I have noticed that if a SSID includes a space the ordering goes off:

import subprocess
import csv

process = subprocess.Popen(['/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport', '-s'], stdout=subprocess.PIPE)
stdout, stderr = process.communicate()

reader = csv.DictReader(stdout.decode('ascii').splitlines(),
                        delimiter=' ', skipinitialspace=True,
                        fieldnames=['wifi_name', 'mac', 'strength'])

for row in reader:
    print(row)

My objective is to get the SSID, mac address and signal strength stored so it can be compared to a spreadsheet.


Solution

  • From airport --help:

    -x        --xml                Print info as XML
    

    Which will output the information in Apple's XML format for property lists, which should be parsable more reliably. Python even comes with a plistlib module which can parse the XML into a Python dictionary:

    #!/usr/bin/env python
    from subprocess import Popen, PIPE
    from plistlib import readPlist
    from pprint import pprint
    
    AirportPath = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport'
    
    proc = Popen([AirportPath, '-s', '-x'], stdout=PIPE)
    
    ssid_data = readPlist(proc.stdout)
    pprint(ssid_data)