From charlesreid1

This covers a second method for connecting to wifi network from the Linux command line (mainly useful for RaspberryPis).

Method 1

Method 1 uses wpa_supplicant to connect to wifi networks: Linux/Wireless

Method 2

While method 1 is purported to work, method 2 works as well. Here's method 2:

Add wpa-ssid and wpa-psk information directly to network interfaces file:

$ cat /etc/network/interfaces

...snip...

auto wlan0
allow-hotplug wlan0
iface wlan0 inet dhcp
wpa-ssid NetName
wpa-psk NetPassword

You should be able to reboot, and the wireless interface should join automatically.

Initially I had problems because I was using a passphrase with several symbols, and was surrounding the passphrase and network name in double quotes. This did not work at all, and I tried many variations on the config file. But as soon as I switched to an alphanumeric passphrase, everything worked perfectly - the wireless interface automatically connected on boot. It was magical.

So the lesson is, IF POSSIBLE, check that your device will connect to the right network automatically.

How To Script It

To script method 2, we can include the contents of files using the source directive, which allows us to put the contents of a wifi network's configuration into a config file, and swap config files in and out as needed on the Pi.

Start with the source directive. We're talking about the /etc/network/interfaces file, so the man page for interfaces tells us about a way to include the contents of one file in another:

Lines beginning with "source" are used to include stanzas from other  files,  so
   configuration can be split into many files. The word "source" is followed by the
   path of file to be sourced. Shell wildcards can be used.   (See  wordexp(3)  for
   details.)

So we can add the following line to /etc/network/interfaces to turn on a particular wifi network configuration:

   source /etc/network/interfaces.d/homenetwork.cfg

The file homenetwork.cfg will contain the wifi configuration:

auto wlan0
allow-hotplug wlan0
iface wlan0 inet dhcp
wpa-ssid NetName
wpa-psk NetPassword

Then we can install the script by running grep on the config file name in /etc/network/interfaces, and if it does not turn up, we add it to the end.

Likewise, to remove it, we run a grep on the config file name in /etc/network/interfaces, and if it does show up, we remove it.

The pi-join-wifi repository will thus contain:

  • config scripts for some public wifi networks
  • example for wpa2 encrypted wifi
  • script to install config script ${1}
  • script to remove config script ${1}

See https://charlesreid1.com:3000/rpi/pi-join-wifi

Flags