Skip to content

Instantly share code, notes, and snippets.

@plusk01
Created April 22, 2019 14:59

Revisions

  1. plusk01 created this gist Apr 22, 2019.
    66 changes: 66 additions & 0 deletions wifi_select.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    #!/bin/bash
    #
    # NetworkManager is trash for robots (periodic scanning causes
    # ~3s latency every 2 minutes). We have disabled Network Manager
    # (systemctl disable network-manager) and network interfaces are
    # now managed via /etc/network/interfaces, with authenticated
    # wireless managed by wpa_supplicant.
    #
    # Your /etc/network/interfaces probably looks like:
    #
    # auto lo
    # iface lo inet loopback
    #
    # auto wlp1s0
    # allow-hotplug wlp1s0
    # iface wlp1s0 inet dhcp
    # wpa_conf /etc/wpa_supplicant/wpa_supplicant.conf
    # wireless-power off
    #
    # Use this script to switch between networks using wpa_supplicant
    # and then to force DHCP renewal.
    #
    # Parker Lusk
    # 19 April 2019

    # Find the available wireless networks that we can connect to
    SSIDs=$(cat /etc/wpa_supplicant/wpa_supplicant.conf | grep ssid | cut -d'"' -f 2)

    # What is the max network id that can be requested?
    NETID_MAX=$(echo -n "$SSIDs" | grep -c '^')
    NETID_MAX=$((NETID_MAX-1))

    function usage {
    echo -e ""
    echo -e "./wifi_select.sh NETID"
    echo -e
    echo -e "\tUse this tool to connect to a wireless network that has been configured"
    echo -e "\tin /etc/wpa_supplicant/wpa_supplicant.conf. The \e[1mNETID\e[0m argument"
    echo -e "\tmust be one of the following network IDs listed below:"
    echo -e ""
    # display each one with its connection number (wpa_cli list_networks)
    count=0
    for ssid in $SSIDs
    do
    echo -e "\t \e[1m$count\e[0m\e[2m: $ssid\e[0m"
    count=$((count+1))
    done
    echo -e ""
    echo -e ""
    }

    # Make sure a valid network id has been supplied
    NETID=$1
    if [ -z "$NETID" ] || (( NETID > NETID_MAX )); then
    usage
    exit -1
    fi

    IFACE=wlp1s0

    wpa_cli -i $IFACE sel $NETID
    sudo dhclient $IFACE > /dev/null 2>&1

    echo -e ""
    echo -e "New IP assigned: $(ip a s $IFACE | sed -En -e 's/.*inet ([0-9.]+).*/\1/p')"
    echo -e ""