Scripting with nmcli to connect RADIUS/WPA2 Enterprise Wi-Fi network

Recently there is a challenge that came from work. A batch of Linux client machines that are going to be deployed onsite need to connect to enterprise Wi-Fi with RADIUS authentication server.

Due to the sheer number of client machines, it is impractical to configure them individually using NetworkManager's GUI. So I decided to write a small script that automates this process by utilizing the command-line interface of NetworkManager: nmcli.

The script is very straightforward: it reads the desired IP address, turns on Wi-Fi radio and connect to a pre-configured Wi-Fi network with static IP and manual DNS/gateway settings.

#!/bin/bash

currentstaticip=$(ip -4 --brief address | grep -m1 192.168 | awk '{print $3}')
echo "The static IP address of $HOSTNAME is $currentstaticip"

# Turn Wi-Fi on and scan for Wi-Fi signals
nmcli radio wifi on
sleep 3

# Configure wlan0 connection
nmcli con modify wlan0 802-11-wireless.ssid THE-SSID

nmcli con modify wlan0 802-1x.eap peap 802-1x.identity THE-IDENTITY \
802-1x.password THE-PASSWD \
802-1x.phase2-auth mschapv2 \
802-11-wireless-security.key-mgmt wpa-eap

nmcli con modify wlan0 ipv4.method manual
nmcli con modify wlan0 ipv4.address $currentstaticip
nmcli con modify wlan0 ipv4.dns 8.8.8.8,1.1.1.1
nmcli con modify wlan0 ipv4.gateway 192.168.x.1

# Connect
nmcli con up "wlan0"
nmcli con modify "wlan0" wifi.hidden yes

The only part that required trial and error is the sequence in which security and identity information is supplied to the RADIUS server. Every RADIUS setup is different and what worked in this scenario may not work under a different setup. On the other hand, there's not a lot of scripting examples out on the internet that deal with enterprise Wi-Fi. All in all, it took me a few hours to read the man pages and come up with this solution.

Hope it will bring value to people who are struggling with similar problems.