I have an old ASUS A43SV that serves as my 16GB 4-core 8-thread public server, hosting http://news.benyamin.xyz and other services that don’t require high uptime/SLA. This device resides in my bedroom with a WiFi connection and is connected to a VPN with a Public IP. As we know, residential areas sometimes experience electricity or internet outages that interrupt the WiFi connection. I’ve been manually reconnecting on-site, but sometimes that’s a hassle. Then I thought of a way to automate this by checking the connection at regular intervals. When the connection is down, it will try to reconnect again.
Fedora Linux/RHEL derivatives use nmcli
to handle network connections. It’s simply:
sudo nmcli con up "connection name"
This is very different compared to Ubuntu/Debian or other Linux distributions, but the basic idea is handled by nmcli
. We can also check the connection by running:
nmcli -f GENERAL.STATE con show "connection name" | grep "activated"
GENERAL.STATE:activated
If the output shows “activated”, then we can assume the WiFi connection is active and connected (although this doesn’t guarantee internet connectivity, it confirms the WiFi link is established).
Based on this idea, I thought of creating a simple bash script that activates the connection when the WiFi connection is down, for example:
#!/bin/bash
CONNAME="Connection Name" # Replace with your actual connection name
# Check connection state using nmcli
# Note: The output format might vary slightly, adjust the check if needed.
if nmcli -f GENERAL.STATE con show "$CONNAME" | grep -q "activated"; then
# Connection is active, do nothing
exit 0
else
# Connection is not active, attempt to bring it up
echo "$(date): Connection '$CONNAME' is down. Attempting to reconnect."
sudo nmcli con up "$CONNAME"
# Optional: Add a small delay before checking again or just let cron handle it
# sleep 5
fi
Save this script as ~/.local/bin/wifi-reconnect.sh
. Then, make it executable using chmod +x ~/.local/bin/wifi-reconnect.sh
and add it to your crontab, for example:
# Wifi Reconnect - Run every minute
* * * * * /home/<your_username>/.local/bin/wifi-reconnect.sh >> /tmp/wifi-reconnect.log 2>&1
And the last step is, since it needs sudo privileges to manage connections, we need to allow the user to run nmcli
with sudo without a password. This can be done by adding an entry for nmcli
in the sudoers configuration, for example in a new file like /etc/sudoers.d/nmcli
:
<username> ALL=NOPASSWD: /usr/bin/nmcli
And there you have it! This setup will help ensure your Raspberry Pi or any old laptop serving as a server maintains its WiFi connection, even if the WiFi Access Point goes down temporarily with automatically reconnecting.
This code is inspired by Auto Reconnect WiFi: Raspberry Pi Note (thanks to author).
Leave a Reply. I will come back and maybe we can have some conversation 🙂