Sunday, March 22, 2009

Scanning for wireless networks

Two methods to scan for wireless networks. One requires sudo/root, the other requires Network Manager.

#! /usr/bin/env python
"""This python 2.5 script uses iwlist to scan for nearby wireless networks. It must be run as sudo/root to work."""
import subprocess as SU
command = ['iwlist', 'eth1', 'scan']
output = SU.Popen(command, stdout=SU.PIPE).stdout.readlines()
data = []
for item in output:
    print item.strip()
    if item.strip().startswith('ESSID:'): 
        data.append(item.lstrip(' ESSID:"').rstrip('"\n'))
    if item.strip().startswith('Quality'): 
        data.append(int(item.split()[0].lstrip(' Quality=').rstrip('/100 ')))
    if item.strip().startswith('Encryption key:off'): data.append('OPEN')
    if item.strip().startswith('Encryption key:on'): data.append('encrypted')        
print data

#! /usr/bin/env python
"""This python 2.5 script uses dbus to query Network Manager, which scans regularly for wireless networks. It does NOT require root/sudo."""
import dbus
item = 'org.freedesktop.NetworkManager'
path = '/org/freedesktop/NetworkManager/Devices/eth1'
interface = item + '.Device'

bus = dbus.SystemBus()
data = []
wireless = dbus.Interface(bus.get_object(item, path), interface)
for network_path in wireless.getNetworks():
    network = dbus.Interface(bus.get_object(item, network_path), interface)
    data.append(network.getName())                        # also network.getProperties[1]
    data.append(network.getStrength())                    # also network.getProperties[3]
    if network.getEncrypted(): data.append('encrypted')
    else: data.append('OPEN')
print data

No comments: