Sunday, November 1, 2015

Connecting to WIFI from commandline in Linux

For the longest time I was unable to properly connect to any WPA2 enabled WiFi from Linux from pure command line in Ubuntu/Fedora, and had to rely exclusively on NetworkManager. While NetworkManager does a good job of connecting to new networks etc, I wanted more control over the connection process, since I was trying to configure my old thinkpad as a secondary router. In this aspect NetworkManager added unnecessary layers of complexity and opaqueness to the whole process, and frankly sucked.

So after a very long time I was able to properly figure out the simplest set of commands (Run as root user/sudo). Hopefully this helps folks who are trying to manually configure the network.


#!/bin/bash

set -ex

# This can be any file used in the wpa_supplicant command.
WPA_SUPPLICANT_PID_FILE=/var/run/wpa_supplicant.pid
WPA_CONFIG_FILE=/etc/wpa_supplicant.conf

# You can get it from lsmod.
WLAN_MODULE=iwl3945

# You network specific configuration.
IFACE=wlan0
SSID=
LOCAL_IP=
NETMASK=
ROUTER_IP=

# Cleans up any previous state (Optional)
modprobe -r ${WLAN_MODULE}
modprobe ${WLAN_MODULE}

# wpa_supplicant requires the interface to be up.
ifconfig ${IFACE} up

# Do not restart wpa_supplicant if this exists.
if [ ! -f ${WPA_SUPPLICANT_PID_FILE} ]; then
        wpa_supplicant -c${WPA_CONFIG_FILE} -B -i${IFACE} -Dnl80211 -P${WPA_SUPPLICANT_PID_FILE}
fi

# Configure static ip.
ifconfig ${IFACE} ${LOCAL_IP} netmask ${NETMASK} up

# Exit at this point if you want to prevent this from accessing the internet.
# exit 0

# Configure default route.
route add default gw ${ROUTER_IP}

# Add Google's DNS servers for name resolutions, coz comcast's DNS is slow and sucks!
echo nameserver 8.8.8.8 > /etc/resolv.conf
echo nameserver 8.8.4.4 >> /etc/resolv.conf