HOWTO: CSV from iwlist scan output, including encryption method

Intro

Here’s a quick script that will output useful one-line summaries from an AP scan with iwlist on WiFi capable GNU/Linux systems, sorting through unwieldy output and pulling out the important bits.

As opposed to this related topic for CSV from iw output, the script will also determine encryption type ready to interface with cgi scripts, PHP or other application layer contexts.

Code

#!/bin/bash

readonly TMPSCAN=/tmp/scan
readonly NETWORKS=/tmp/networks
readonly  NIC=wlan0

scan () {

rm -f $NETWORKS

iwlist $NIC scan > $TMPSCAN

ssids=($(cat $TMPSCAN | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'))
len=${#ssids[@]}

for ssid in ${ssids[@]}
    do
        cell=$(sed -n "/$ssid/,/Cell\ [0-9]/p" $TMPSCAN)
        # array (chan enc essid)
        cv=($(echo "$cell" | grep -E 'Channel:|Encryption|ESSID:' | sed 's/.*://'))
        chan=${cv[0]}
        enc=${cv[1]}
        essid=${cv[@]:2} # safer all-to-end for wildcards and whitespace in ESSIDs 
        #echo "$cell"
        if [[ $enc == "on" ]]; then
            # If this cell uses WPA
            if [[ "$cell" == *WPA[0-9]\ Version* ]]; then
                enc=wpa
            else
                enc=wep
            fi 
        fi

        if [[ "$essid" == '""' ]]; then
            essid="hidden"
        fi
        
        ## base 64 encode ESSIDs for string safety, as required
        #essid=$(echo $essid | base64) 
        echo $ssid","$essid","$chan","$enc >> $NETWORKS
    done
}                                                                                                                                          

scan
echo "Found the following networks (BSSID,ESSID,CHANNEL,ENC):"
echo "//------------------------------------------------------------->"
cat $NETWORKS
echo "//<-------------------------------------------------------------"

To use

Save it out as scan.sh and make it executable, like so:

chmod +x ./scan.sh

Run like so as root (or with sudo):

./scan.sh

Output is like so:

Found the following networks (BSSID,ESSID,CHANNEL,ENC):
//------------------------------------------------------------->
D4:55:7C:94:D8:94,“KDG-4B88F”,6,wpa
08:96:D7:E9:E0:10,“TheInternet”,7,wpa
40:4D:8E:99:8D:7A,“WMON-8B7A66”,8,wpa
00:17:A5:EF:B5:12,“unplug_B512”,11,wpa
00:15:6D:10:84:D0,“freinet”,11,off
A0:E4:4D:96:1F:CC,“Krokodil24”,15,wpa
F4:5F:DD:7D:3C:AD,“DIRECT-AC-HP ENVY 4520 series”,8,wpa
48:0E:14:A2:95:52,“FRITZ!Dox 5490 Cable”,11,wpa
5A:0E:14:A2:93:52,“Vodafone Hotspot”,11,off
58:8D:F5:1F:69:57,“o2-WLAN68”,12,wep
FA:8F:4A:5C:8D:D7,hidden,1,off
00:15:49:D0:FE:D0,“Bundesnachrichtendienst”,6,wpa
//<--------------------------------------------------------------