I just wrote a script that extracts wifi passwords from the system, how can I improve that script and make it cleaner ?
import subprocess
import shlex
import os
file_path = "/etc/NetworkManager/system-connections/"
wifi_data = os.listdir(file_path)
print(" ")
data = []
for file in wifi_data:
spaceless_wifi_path_data = file.replace(" ", "\\ ")
cmd = f"cat /etc/NetworkManager/system-connections/{spaceless_wifi_path_data}"
args = shlex.split(cmd)
p = subprocess.Popen(args,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
data.append(p)
parsed_data = str([data[i].communicate() for i in range(len(data))]).split("\\")
wifi_id_list = [line[4:] for line in parsed_data if 'nid' in line]
keys = [keys[5:] for keys in parsed_data if "npsk" in keys]
gap = len(wifi_id_list) - len(keys)
for missing in range(gap):
keys.append("No keys has found")
results = list(zip(wifi_id_list[::-1], keys))
for ID, PASS in results:
print(f"WiFi ID: {ID}, Password: {PASS}")
How this code can improved in terms of less used variables and more list comprehensions. It just feels like not convineant to read.
You don't need to use cat and start a subprocess to read the content of a file. This simplifies the script a bit. I also think that list comprehension isn't suited for this task and you should just build the result while iterating over the files.
import os
path = "/etc/NetworkManager/system-connections/"
wifi_id = []
keys = []
for file in os.listdir(path):
with open(path + file, 'r') as f:
content = f.read()
for line in content.split('\n'):
if line.startswith("nid"):
wifi_id.append(line[4:])
if line.startswith("npsk"):
keys.append(line[5:])
if len(keys) != len(wifi_id):
keys.append("Keys not found")
results = list(zip(wifi_id, keys))