Bash Through Examples: Practical Learning of Linux Scripts by Gonzalez Dominguez Tomas

Bash Through Examples: Practical Learning of Linux Scripts by Gonzalez Dominguez Tomas

Author:Gonzalez Dominguez, Tomas
Language: eng
Format: epub
Published: 2024-02-03T00:00:00+00:00


Develop a Bash script to monitor network activity on a specific interface and log any excess data usage beyond a user-defined threshold.

The script must allow the user to specify the network interface and data threshold (in MB) as arguments. If data usage exceeds the threshold in a given period of time, this event must be recorded in a log file.

Bash Script Solution

This script will use `vnstat` to monitor network usage on the specified interface. `vnstat` is a console tool that keeps track of network usage, so it must be installed on the system for this script to work correctly. The script will check data usage at regular intervals and log any excess of the threshold to a log file.

bash

#!/bin/bash

# Verify that the necessary arguments have been provided

if [ "$#" -ne 2 ]; then

echo "Usage: $0 network_interface MB_threshold"

exit 1

be

interface=$1

threshold=$(($2*1024)) # Convert MB to KB to compare with vnstat

# Log file name

log_file="exceeded_network_usage.log"

# Feature to check data usage and log overages

verify_usage() {

# Get the total KB received and transmitted in the current month

fashion=$(vnstat -i $interface --oneline | cut -d ';' -f 3.4 | tr ';' '+' | bc);

if [ "$use" -gt "$threshold" ]; then

# Log excess usage

echo "$(date +"%Y-%m-%d %H:%M:%S"): Excessive usage on $interface - ${usage}KB exceeds ${threshold}KB threshold" >> $ log_file

echo "Alert: Excessive data usage recorded."

else

echo "Data usage is within the set limit."

be

}

# Monitor network usage every 10 minutes

while true; do

verify_usage

sleep 600

done

How to Use the Script

1. Make sure `vnstat` is installed on your system. If it is not installed, you can install it using your distribution's package manager, for example, `sudo apt-get install vnstat` on Debian/Ubuntu.

2. Save the script to a file, for example `monitor_red.sh`.

3. Give the file execute permissions with `chmod +x monitor_red.sh`.

4. Run the script providing the network interface and data threshold in MB as arguments. For example:

bash

./monitor_red.sh eth0 500

This script is useful for system administrators or users interested in keeping tabs on network usage, especially on connections with data limits or to identify unusual activity on their networks.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.