Search code examples
bashparsingsedawk

Parsing iw wlan0 scan output


I wrote wlan manager script to handle open/ad-hoc/wep/wpa2 networks. Now im trying to parse iw wlan0 scan output to get nice scan feature to my script. My goal is to get output like this :

SSID        channel     signal      encryption
wlan-ap     6           70%         wpa2-psk
test        1           55%         wep

What i have achived already is output like this :

$ iw wlan0 scan | grep 'SSID\|freq\|signal\|capability' | tac
SSID: Koti783
signal: -82.00 dBm
capability: ESS Privacy ShortPreamble SpectrumMgmt ShortSlotTime (0x0531)
freq: 2437

I have been trying to study bash/sed/awk but havent found yet a way to achieve what im trying. So what is good way to achieve that?


Solution

  • Here is my final solution based of Sudo_O answer:

    $1 == "BSS" {
        MAC = $2
        wifi[MAC]["enc"] = "Open"
    }
    $1 == "SSID:" {
        wifi[MAC]["SSID"] = $2
    }
    $1 == "freq:" {
        wifi[MAC]["freq"] = $NF
    }
    $1 == "signal:" {
        wifi[MAC]["sig"] = $2 " " $3
    }
    $1 == "WPA:" {
        wifi[MAC]["enc"] = "WPA"
    }
    $1 == "WEP:" {
        wifi[MAC]["enc"] = "WEP"
    }
    END {
        printf "%s\t\t%s\t%s\t\t%s\n","SSID","Frequency","Signal","Encryption"
    
        for (w in wifi) {
            printf "%s\t\t%s\t\t%s\t%s\n",wifi[w]["SSID"],wifi[w]["freq"],wifi[w]["sig"],wifi[w]["enc"]
        }
    }'
    

    Output:

    $ sudo iw wlan0 scan | awk -f scan.awk
    SSID        Frequency   Signal      Encryption
    netti       2437        -31.00 dBm  Open
    Koti783     2437        -84.00 dBm  WPA
    WLAN-AP     2462        -85.00 dBm  WPA