Saturday, January 28, 2017

Temporarily switching Wi-Fi networks from the command line on a Raspberry Pi

I recently had a scenario with my Raspberry Pi (Zero, running Raspbian) where I needed to temporarily switch away from the primary Wi-Fi connection to another access point (to drive a camera) then reconnect to my original network. Turns out wpa_cli can do the trick:

#!/bin/bash
# Worked example of temporarily switching from a configured network in
# wpa_supplicant.conf to a new network to perform an operation, then returning
# to the original network. An example of this configuration would
# be:
# https://learn.adafruit.com/pi-wifi-radio/raspberry-pi-setup-1-of-3#configure-wireless-networking
#
# Assumes that running `wpa_cli list_networks` will return a single network at
# index 0, the one you want to always be connected to at boot up.
#
# You'll need to replace [SSID] and [PASSWORD] (including square brackets)
# with appropriate values, you must keep the single and double inverted
# commas though.
#
# The `wpa_cli add_network` will add a new network every time, but we ignore
# this and just use the first one after the pre-configured one at index 0.
# Connect to new network
sudo wpa_cli add_network
sudo wpa_cli set_network 1 ssid '"[SSID]"'
sudo wpa_cli set_network 1 psk '"[PASSWORD]"'
sudo wpa_cli select_network 1
# Do stuff on that network
# ...
# Return to the original network
sudo wpa_cli select_network 0
The best thing about this approach is that it is non-persistent, so if it all goes horrible wrong you get your original networking configuration back upon reboot.