Check Whenever Wifi Is Connected and Send Email When Its Connected

Thank you for providing the information and the modified Bash script. Below, I’ll provide a breakdown of the script’s functionality and highlight the changes made for clarity. This will be presented in Markdown format as requested.


Bash Script: Check WiFi Connection and Send Email

This Bash script checks whether the WiFi connection is active and sends an email when it reconnects. Here’s an overview of the script’s key points and improvements:

Email Sending

The script has been enhanced to include email sending functionality using the mail command. Ensure you replace '[email protected]' with your actual email address.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/bin/bash

# Check if WiFi is not associated (disconnected)
if /sbin/iwconfig wlan0 | grep -o "Access Point: Not-Associated" > /dev/null
then
    # If there's no downtime record, create one
    if [ ! -f ~/.downtime ]
    then
        date > ~/.downtime
    fi
    # Restart the network manager (requires sudo)
    sudo service network-manager restart > /dev/null
else
    # If WiFi was previously disconnected, send an email
    if [ -f ~/.downtime ]
    then
        disconnected_date=$(<~/.downtime)
        connected_date=$(date)
        rm ~/.downtime

        # Send an email
        mail -s "WiFi Reconnected" [email protected] <<EOF
        WiFi was disconnected at: $disconnected_date
        WiFi reconnected at: $connected_date
        EOF
    fi
fi

Command Syntax

The script uses commands like iwconfig and service that require administrative privileges (sudo). Ensure that the script is executed with the appropriate permissions.

Logging

The script logs downtime and uptime information in a file (~/.downtime). Ensure that your script has write access to this location (~ refers to the home directory of the user running the script).

Error Handling

Consider adding error handling to your script, especially for commands like iwconfig and service to log errors for debugging purposes.

Configuration

This script assumes you have a functioning mail command on your system, and it uses the local mail transfer agent (MTA). Configure your system’s email settings for proper functionality.

Automation

Consider setting up a cron job to run this script periodically if you want continuous monitoring.


By implementing these changes and considerations, your Bash script can effectively monitor WiFi connectivity and send email notifications when the connection is reestablished.

0%