Skip to content

Instantly share code, notes, and snippets.

@TheLandolorien
Created December 14, 2017 13:11
Show Gist options
  • Save TheLandolorien/d1cc9d0cf654cb7b8cd207daf589c977 to your computer and use it in GitHub Desktop.
Save TheLandolorien/d1cc9d0cf654cb7b8cd207daf589c977 to your computer and use it in GitHub Desktop.
Raspberry Pi Wi-Fi Configuration Script via wpa_supplicant.conf
#!/bin/bash
usage() {
echo ""
echo "Raspberry Pi Wi-Fi Configuration Script"
echo "====================================================================="
echo "This script stores a secure version of your Wi-Fi network password"
echo "and automatically configures your Raspberry Pi to connect to the "
echo "provided Wi-Fi network name."
echo ""
echo "Usage: $0 -s <SSID>";
echo "-s | SSID (Wi-Fi Network Name) surrounded in quotation marks" 1>&2; exit 1;
}
while getopts ":s:" o; do
case "${o}" in
s)
ssid=${OPTARG}
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
if [ "$(id -u)" != "0" ]; then
echo "This script must be run with root privileges."
echo "Try: sudo $0 -s <SSID>" 1>&2; exit 1;
fi
if [ -z "${ssid}" ]; then
usage
fi
sed -i ':again;$!N;$!b again; s/network={[^}]*}//g' /etc/wpa_supplicant/wpa_supplicant.conf
sed -i 's/Passphrase must be 8\.\.63 characters//g' /etc/wpa_supplicant/wpa_supplicant.conf
echo -n "Enter Wi-Fi Password, followed by [ENTER]: "
read -s wifipasswd
echo ""
wifi_config=`wpa_passphrase "${ssid}" "${wifipasswd}" | awk 'NR != 3 { print }'`
echo "${wifi_config}" >> /etc/wpa_supplicant/wpa_supplicant.conf
connection_status=`wpa_cli reconfigure | awk 'NR == 2 { print }'`
case "$connection_status" in
OK)
sleep 10
ip_addr=`ifconfig wlan0 | awk '/inet addr/{ print substr($2,6) }'`
if [ -z "$ip_addr" ]; then
echo "Wi-Fi Connection unsuccessful."
echo "Check your check your Wi-Fi password."
else
echo "Wi-Fi Connection successfully established."
fi
;;
FAIL)
echo "Wi-Fi Connection failed."
echo "Make sure the SSID is surrounded in quotation marks and that your "
echo "Wi-Fi password is 8 - 63 characters long."
usage
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment