Skip to content

Instantly share code, notes, and snippets.

@thisismyrobot
Last active May 12, 2020 08:50
Show Gist options
  • Save thisismyrobot/a9c6185bf344c017f36d9d79b7c0f185 to your computer and use it in GitHub Desktop.
Save thisismyrobot/a9c6185bf344c017f36d9d79b7c0f185 to your computer and use it in GitHub Desktop.
Temporarily switching Wi-Fi networks from the command line on a Raspberry Pi
#!/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
@sourcevault
Copy link

What is the difference between select_network and enabe_network ?

@thisismyrobot
Copy link
Author

@sourcevault I think the enable_network is unnecessary, in retrospect. At the time I thought I needed it but I did some digging and select_network does everything that enable_network does, and disables the other networks - which is the point of the script. I just didn't know that at the time. I'll amend the Gist appropriately - thank you.

@ScottBruton
Copy link

Hi @thisismyrobot.

Maybe you can help me.
When I run the wpa_cli and execute the following:

add_network
1
set_network 1 ssid "myssid"
set_network 1 psk "mypswd"
save_config
quit

and then open my wpa_supplicant.config file. The new network that I have added, has overwritten my old network in the config file. How would I get it to add a network below the original network like I feel that it should?

SIDE NOTE:
It allows me to enable_network 0 and enable_network 1, which suggests that it has saved it somewhere, but where if not the wpa_supplicant.conf file?

Thanks for your help in advance.
Scott

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment