Automatically Reconnecting to WiFi in Fedora 39

2024-02-17 2024-09-22history

Table of Contents

I set up an N100 mini PC as a server to sync files between multiple devices, running Fedora 39. However, connection to the WiFi at home is lost from time to time, so I need a script to automatically reconnect.

1. The Bash script

ChatGPT wrote me a perfect script for detecting loss of connection and automatic reconnecting:

#!/bin/bash

# Replace "your_wifi_connection_name" with your actual WiFi connection name

WIFI_CONNECTION="your_wifi_connection_name"

# Check if the WiFi is connected
if ! nmcli connection show --active | grep -q "$WIFI_CONNECTION"; then
    echo "WiFi disconnected. Reconnecting..."

    # Attempt to reconnect
    nmcli connection up "$WIFI_CONNECTION"
else
    echo "WiFi is already connected."
fi

To allow this script to be executed, type in terminal:

chmod +x <path-to-the-script-above>

We can manually test whether this script is working by disconnecting WiFi and type in the terminal:

bash <path-to-the-script-above>

The WiFi should re-connect.

2. Creating a Cron job and resolving authority issues

The next step is to create a cron job to run this script every minute. In the terminal, type:

crontab -e

and add the following line:


*/1 * * * * bash <path-to-the-script-above>

and save and exit.

We can test by manually disconnect WiFi and see if it reconnects within one minute. However, this may not work because cron may not have the right authority to reconnect. To check if this is truly the issue, type in the terminal:

sudo cat /var/log/cron

If the output contains information like: CMDOUT (Error: Connection activation failed: Not authorized to control networking.), cron doesn’t have the right authority.

In this case, to further check which authority is missing, run crontab -e again and add the following line:


*/1 * * * * nmcli general permissions > <output-path-and-filename-as-you-like>

and save and exit. Then, in the terminal, type:

cat <output-path-and-filename-above>

which should contain a line saying:


org.freedesktop.NetworkManager.network-control                    auth

and we want this value to be yes.

To give cron the authority, following the solution in this link, I added a x.pkla file to /etc/polkit-1/localauthority/50-local.d/:


[Let wheel group modify system settings for network]
Identity=unix-group:wheel
Action=org.freedesktop.NetworkManager.network-control
ResultAny=yes

Note that the group name wheel may depend on the system. In the link’s example, the name is adm.

Then we need to reload polkit by typing in the terminal:

systemctl restart polkit

Now manually disconnect, and it should reconnect within one minute!


Author: Yu Huo (yhuo@tuta.io) Create Date: 2024-02-17 Last modified: 2024-09-22 Creator: Emacs 29.2 (Org mode 9.7.11)