Reputation: 1236
I can't get an output from this code, it is just looping infinitely I guess, it has to readlines and append those lines to the list named data, but it doesn't give an output, what have I done wrong? Any suggestions will be appreciated, thanks in advance.
import os
import subprocess
import commands
command = ['sudo', 'iwlist', 'wlan0', 'scan']
output = subprocess.Popen(command, stdout=subprocess.PIPE).stdout.readlines()
data = []
for item in output:
if item.strip().startswith('ESSID:'):
data = (item.lstrip('ESSID:').rstrip('\n'))
for item in output:
if item.strip().startswith('Quality:'):
data.append('Quality:')
for item in output:
if item.strip().startswith('Pairwise:'):
data.append('Pairwise:')
print data
Upvotes: 1
Views: 137
Reputation: 76887
Try the code below, I don't think you need multiple for
loops.
Also, the command iwlist
works without sudo
permissions as well, so you should cut it out (since you won't be able to enter the sudo password with subprocess.PIPE
)
I've also removed os
, commands
modules which though imported are not being used anywhere.
import subprocess
command = ['iwlist', 'wlan0', 'scan']
output = subprocess.Popen(command, stdout=subprocess.PIPE).stdout.readlines()
data = []
for item in output:
if item.strip().startswith('ESSID:'):
data.append([item.lstrip('ESSID:').rstrip('\n')])
if item.strip().startswith('Quality:'):
data.append('Quality:')
if item.strip().startswith('Pairwise:'):
data.append('Pairwise:')
print data
EDIT
Since you want to read each of the connections, try this one
import subprocess
command = ['sudo', '-S', 'iwlist', 'wlan0', 'scan']
output = subprocess.Popen(command, stdout=subprocess.PIPE).stdout.read()
data = []
for cell_item in output.split("Cell"):
data_item = []
for line in cell_item.split("\n"):
if any(item in line for item in ["ESSID", "Quality", "Pairwise"]):
data_item.append(line.strip())
if data_item:
data.append(data_item)
print data
The trick here is to split the output by cells first (based on output of iwlist on my system), and then, within each of the cell, you can check for Quality, Pairwise, ESSID
.
Upvotes: 3