Switch between WiFi networks without reboot, command line

Today I have a chalange to set up WiFi connection on Raspbian Stretch Lite operating system.

While I testing it is nice to have:
  • Right keyboard layout by default
  • Auto login pi user
For fast wifi connection I can put the configuration on /boot/first/wpa_supplicant.conf
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="first-network"
psk="AwwEsom3"
}
and also I have second configuration on /boot/second/wpa_supplicant.conf
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="second-network"
psk="Hello123"
}
Here is what I have learned:

Every file which will be placed in /boot/wpa_supplicant.conf will be automatically moved to /etc/wpa_supplicant/wpa_supplicant.conf
So I will place my configurations in subdirectory :)

By default /etc/network/interface is empty like this:
# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d
and "/etc/network/interfaces.d" actually is empty directory So how do I move to another wifi network without rebooting pi?

Let's replace all content in "/etc/network/interfaces" with something else:
cat > /etc/network/interfaces <<EOF

#let wifi interface request IP address by himself
iface wlan0 inet dhcp

#tell where all wifi credentials are in
wpa_conf /etc/wpa_supplicant/wpa_supplicant.conf

#execute wlan0 configuration everytime network service is restarted. very important
auto wlan0

EOF
Now I can switch between networks with
cp /boot/first/wpa_supplicant.conf /etc/wpa_supplicant
/etc/init.d/networking restart
or
cp /boot/second/wpa_supplicant.conf /etc/wpa_supplicant
/etc/init.d/networking restart
If something is not working at all then kill wpa_supplicant:
rm /var/run/wpa_supplicant/wlan0
pkill wpa_supplicant

No comments: