Skip to content

Instantly share code, notes, and snippets.

@bartimusprimed
Created January 11, 2021 13:48
Show Gist options
  • Save bartimusprimed/69ed191f2a5b9d3172581b715bb616d5 to your computer and use it in GitHub Desktop.
Save bartimusprimed/69ed191f2a5b9d3172581b715bb616d5 to your computer and use it in GitHub Desktop.
Simple iw parser in python. Useful for getting wireless card capabilities on linux.
import os
from pprint import pprint
from typing import Dict
# mac_addr = re.compile(r"[A-z0-9]+[:][A-z0-9]+")
def get_iw_output() -> Dict:
delimiter = "phy#"
interfaces = [x.replace("\t", "").replace("\n", "") for x in os.popen("iw dev").readlines()]
devices = {}
master_devices = {}
current_interface = ""
for item in interfaces:
if delimiter in item:
master_devices[item] = {}
devices[item] = {}
current_interface = item
else:
item = item.split(" ")
k, v = "", ""
if len(item) == 2:
k, v = item[0], item[1]
if v:
master_devices[current_interface][k] = v
for key in devices.keys():
devices[key] = [x.replace("\t", "").replace("\n", "").strip() for x in os.popen(f"iw {key} info").readlines()]
cleaned_dictionary = {}
in_tag = False
current_parent = ""
for dev, info in devices.items():
cleaned_dictionary[dev] = {}
for x in info:
if "*" in x and current_parent and in_tag:
# need to take care of these op codes that iw outputs
x = x.lstrip("* ")
if ":" in x:
x = x.split(":")[0]
cleaned_dictionary[dev][current_parent].append(x)
else:
if ":" in x:
k,v = x.split(":")
k = k.strip()
v = v.strip()
if v:
cleaned_dictionary[dev][k] = v
else:
in_tag = True
current_parent = k
cleaned_dictionary[dev][k] = []
for key in master_devices.keys():
if cleaned_dictionary[key] is not None:
master_devices[key]["INFO"] = cleaned_dictionary[key]
return master_devices
if __name__ == "__main__":
get_iw_output()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment