Fetching WiFi Configs on Raspberry Pi

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.


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

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev

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():
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
networks = wpa_conf.networks()
return networks

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

('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.



All my stories have moved to https://maskaravivek.com/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store