Fetching WiFi Configs on Raspberry Pi

Vivek Maskara
2 min readAug 27, 2022

--

Photo by Harrison Broadbent on Unsplash

In this short post, we will learn how to fetch a list of configured Wifi networks on your Raspberry Pi.

If you are looking to configure Wifi on the Raspberry Pi then refer to this post.

The Wifi config on a Raspberry Pi is stored in the wpa_supplicant.conf file.

/etc/wpa_supplicant/wpa_supplicant.conf

The wpa_supplicant.conf file contents should look something like this:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=US
network={
ssid="<YOUR_WIFI_NAME>"
psk="<YOUR_WIFI_PASSWORD>"
}
network={
ssid="<YOUR_WIFI_NAME_2>"
psk="<YOUR_WIFI_PASSWORD_2>"
}

Let us get started and learn how to work with the wifi configs.

Step 1: Install wpasupplicantconf

Install the wpasupplicantconf lib for parsing the wpa_supplicant.conf file.

pip install wpasupplicantconf

Step 2: Read the config file

Next, read the plain text file contents from the wpa_supplicant.conf

def get_wifi_config():
file = open('/etc/wpa_supplicant/wpa_supplicant.conf', 'r')
lines = file.readlines()
return lines

Step 3: Get Configured Networks

Finally, we can get a list of configured networks as follows

from wpasupplicantconf import WpaSupplicantConf, ParseErrordef get_wifi_networks():
try:
lines = get_wifi_config()
wpa_conf = WpaSupplicantConf(lines)
network_keys = list(wpa_conf.networks().keys())
if len(network_keys) == 0:
print('no wifi network configured')
return None
else:
networks = wpa_conf.networks()
return networks

That’s it. It will return you an OrderedDict of networks as follows.

OrderedDict([
('Wifi1', OrderedDict([('psk', '"Password1"')])),
('Wifi2', OrderedDict([('psk', '"Password1"')]))
])

That’s it for this post. Please leave a clap if you found this article useful. Consider subscribing to Medium to read more of my stories.

--

--

No responses yet