Linux Internet Speed Monitor (LISM) - Automated Network Speed Testing Tool

A bash script that checks internet speed periodically and logs the results. This will be useful for monitoring your internet connection over time.

A comprehensive bash script that serves as an alternative to MySpeed. Here’s how to use it:

  1. Save the script as speedtest.sh and make it executable:
chmod +x speedtest.sh
  1. Install dependencies (the script will try to do this automatically, but you can do it manually):
sudo apt-get install speedtest-cli  # For Debian/Ubuntu
# or
sudo yum install speedtest-cli      # For CentOS/RHEL
  1. Set up a cron job to run it periodically. For example, to run every hour:
crontab -e

Then add:

0 * * * * /path/to/speedtest.sh

Features of the script:

  1. Logging System:

    • Main log file: /var/log/speedtest/speedtest.log
    • CSV results: /var/log/speedtest/speedtest_results.csv
    • Error log: /var/log/speedtest/speedtest_errors.log
    • Daily reports: /var/log/speedtest/daily_report_YYYYMMDD.txt
  2. Functionality:

    • Automatically checks and installs dependencies
    • Records ping, download, and upload speeds
    • Generates CSV data for easy analysis
    • Creates daily summary reports
    • Includes timestamp with all measurements
    • Error handling and logging
  3. Daily Reports:

    • Calculates average ping, download, and upload speeds
    • Shows number of tests performed
    • Automatically generated for each day

To monitor your results, you can:

  • Check the CSV file for raw data
  • View daily reports for averages
  • Monitor the main log file for script execution details
  • Check the error log if something goes wrong

The logs will be stored in /var/log/speedtest/. Make sure the user running the script has write permissions to this directory, or modify the LOG_DIR variable to point to a different location.

#!/bin/bash

###############################################################################
#
# Linux Internet Speed Monitor (LISM) - Automated Network Speed Testing Tool
# -----------------------------------------------------------------------
#
# 🚀 A powerful alternative to commercial speed testing tools
# 
# GitHub Tags: 
# #linux-speed-test #network-monitoring #bandwidth-monitor #internet-speed-logger
# #speedtest-automation #network-diagnostics #linux-networking #speed-test-script
# #internet-performance #network-speed-monitor
#
# Description:
# This script provides automated internet speed testing and logging capabilities
# for Linux systems. It's an open-source alternative to commercial speed testing
# tools, offering detailed logging, reporting, and monitoring features.
#
# Features:
# - Automated speed testing at customizable intervals
# - Comprehensive logging system with CSV export
# - Daily performance reports and statistics
# - Email notifications for speed drops (optional)
# - Historical data tracking and analysis
# - Compatible with most Linux distributions
#
# Technical Keywords:
# - Bash Script
# - Speedtest-cli
# - Network Monitoring
# - Performance Testing
# - Automated Testing
# - Linux Systems
# - Cron Integration
# - CSV Data Export
#
# Author: hhf technology
# Version: 1.0.0
# License: MIT
# Last Updated: 11/08/2024
#
# Usage Examples:
# ./speedtest.sh           # Run speed test once
# ./setup.sh              # Complete installation and configuration
#
# Requirements:
# - Linux-based operating system
# - speedtest-cli
# - bash shell
# - root or sudo privileges for installation
#
# For more information and updates:
# GitHub: https://git.hhf.technology
# Documentation: https://forum.hhf.technology
#
###############################################################################

# Configuration
LOG_DIR="/var/log/speedtest"
SCRIPT_LOG="${LOG_DIR}/speedtest.log"
CSV_LOG="${LOG_DIR}/speedtest_results.csv"
ERROR_LOG="${LOG_DIR}/speedtest_errors.log"

# Create necessary directories if they don't exist
mkdir -p "$LOG_DIR"

# Function to log messages
log_message() {
    local message="$1"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] $message" >> "$SCRIPT_LOG"
}

# Function to check if speedtest-cli is installed
check_dependencies() {
    if ! command -v speedtest-cli &> /dev/null; then
        log_message "ERROR: speedtest-cli is not installed. Installing now..."
        if command -v apt-get &> /dev/null; then
            sudo apt-get update && sudo apt-get install -y speedtest-cli
        elif command -v yum &> /dev/null; then
            sudo yum install -y speedtest-cli
        else
            log_message "ERROR: Could not install speedtest-cli. Please install it manually."
            exit 1
        fi
    fi
}

# Function to run speed test
run_speed_test() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local date_for_filename=$(date '+%Y%m%d')
    
    log_message "Starting speed test..."
    
    # Run speedtest and capture output
    if ! speedtest_output=$(speedtest-cli --simple 2>> "$ERROR_LOG"); then
        log_message "ERROR: Speed test failed. Check error log for details."
        return 1
    fi
    
    # Parse speedtest output
    ping=$(echo "$speedtest_output" | grep 'Ping' | awk '{print $2}')
    download=$(echo "$speedtest_output" | grep 'Download' | awk '{print $2}')
    upload=$(echo "$speedtest_output" | grep 'Upload' | awk '{print $2}')
    
    # Create CSV header if file doesn't exist
    if [ ! -f "$CSV_LOG" ]; then
        echo "Timestamp,Ping (ms),Download (Mbps),Upload (Mbps)" > "$CSV_LOG"
    fi
    
    # Log results to CSV
    echo "${timestamp},${ping},${download},${upload}" >> "$CSV_LOG"
    
    # Log results to main log file
    log_message "Speed test completed:"
    log_message "Ping: ${ping} ms"
    log_message "Download: ${download} Mbps"
    log_message "Upload: ${upload} Mbps"
    
    # Create daily report
    generate_daily_report "$date_for_filename"
}

# Function to generate daily report
generate_daily_report() {
    local date_str="$1"
    local daily_report="${LOG_DIR}/daily_report_${date_str}.txt"
    
    # Calculate daily averages
    local daily_stats=$(awk -F',' -v date="$(date '+%Y-%m-%d')" '
        BEGIN {ping_sum=0; down_sum=0; up_sum=0; count=0}
        $1 ~ date {
            ping_sum+=$2; 
            down_sum+=$3; 
            up_sum+=$4; 
            count++
        }
        END {
            if (count > 0) {
                printf "Daily Averages (%s):\n", date;
                printf "Ping: %.2f ms\n", ping_sum/count;
                printf "Download: %.2f Mbps\n", down_sum/count;
                printf "Upload: %.2f Mbps\n", up_sum/count;
                printf "Number of tests: %d\n", count
            }
        }' "$CSV_LOG")
    
    echo "$daily_stats" > "$daily_report"
    log_message "Daily report generated: $daily_report"
}

# Main execution
main() {
    log_message "Starting speed test script..."
    
    # Check dependencies
    check_dependencies
    
    # Run speed test
    run_speed_test
    
    log_message "Script execution completed."
}

# Execute main function
main

with cron job

#!/bin/bash

# Configuration
INSTALL_DIR="/opt/speedtest-monitor"
SCRIPT_NAME="speedtest.sh"
LOG_DIR="/var/log/speedtest"
USER=$(whoami)

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print colored messages
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# Function to check if running as root
check_root() {
    if [ "$EUID" -ne 0 ]; then
        print_message $RED "Please run this script as root or with sudo"
        exit 1
    fi
}

# Create necessary directories
setup_directories() {
    print_message $YELLOW "Creating directories..."
    mkdir -p "$INSTALL_DIR"
    mkdir -p "$LOG_DIR"
    
    # Set appropriate permissions
    chown -R $USER:$USER "$INSTALL_DIR"
    chown -R $USER:$USER "$LOG_DIR"
    chmod 755 "$INSTALL_DIR"
    chmod 755 "$LOG_DIR"
    
    print_message $GREEN "Directories created successfully"
}

# Install dependencies
install_dependencies() {
    print_message $YELLOW "Installing dependencies..."
    
    if command -v apt-get &> /dev/null; then
        apt-get update
        apt-get install -y speedtest-cli
    elif command -v yum &> /dev/null; then
        yum install -y speedtest-cli
    else
        print_message $RED "Could not detect package manager. Please install speedtest-cli manually"
        exit 1
    fi
    
    print_message $GREEN "Dependencies installed successfully"
}

# Setup cron job
setup_cron() {
    local frequency=$1
    local cron_entry=""
    
    case $frequency in
        "hourly")
            cron_entry="0 * * * * $INSTALL_DIR/$SCRIPT_NAME"
            ;;
        "half-hourly")
            cron_entry="0,30 * * * * $INSTALL_DIR/$SCRIPT_NAME"
            ;;
        "every-15-min")
            cron_entry="*/15 * * * * $INSTALL_DIR/$SCRIPT_NAME"
            ;;
        "daily")
            cron_entry="0 0 * * * $INSTALL_DIR/$SCRIPT_NAME"
            ;;
        *)
            print_message $RED "Invalid frequency specified"
            exit 1
            ;;
    esac
    
    # Remove any existing cron jobs for the script
    crontab -l | grep -v "$SCRIPT_NAME" | crontab -
    
    # Add new cron job
    (crontab -l 2>/dev/null; echo "$cron_entry") | crontab -
    
    print_message $GREEN "Cron job set up successfully"
}

# Copy speedtest script to install directory
install_script() {
    if [ ! -f "speedtest.sh" ]; then
        print_message $RED "speedtest.sh not found in current directory"
        exit 1
    fi
    
    cp speedtest.sh "$INSTALL_DIR/$SCRIPT_NAME"
    chmod +x "$INSTALL_DIR/$SCRIPT_NAME"
    print_message $GREEN "Script installed successfully"
}

# Main setup function
main() {
    print_message $YELLOW "Starting setup..."
    
    # Check if running as root
    check_root
    
    # Install dependencies
    install_dependencies
    
    # Setup directories
    setup_directories
    
    # Install script
    install_script
    
    # Ask user for preferred frequency
    echo
    print_message $YELLOW "Please select the frequency for speed tests:"
    echo "1) Hourly (recommended)"
    echo "2) Every 30 minutes"
    echo "3) Every 15 minutes"
    echo "4) Daily"
    
    read -p "Enter your choice (1-4): " choice
    
    case $choice in
        1) setup_cron "hourly" ;;
        2) setup_cron "half-hourly" ;;
        3) setup_cron "every-15-min" ;;
        4) setup_cron "daily" ;;
        *) print_message $RED "Invalid choice"; exit 1 ;;
    esac
    
    echo
    print_message $GREEN "Setup completed successfully!"
    echo
    print_message $YELLOW "Installation Summary:"
    echo "- Script location: $INSTALL_DIR/$SCRIPT_NAME"
    echo "- Log directory: $LOG_DIR"
    echo "- Cron job has been set up as requested"
    echo
    print_message $YELLOW "You can check the logs at:"
    echo "- Main log: $LOG_DIR/speedtest.log"
    echo "- CSV results: $LOG_DIR/speedtest_results.csv"
    echo "- Error log: $LOG_DIR/speedtest_errors.log"
    echo "- Daily reports: $LOG_DIR/daily_report_YYYYMMDD.txt"
}

# Run main function
main

I’ve created a setup script that will automate the entire installation process. Here’s how to use it:

  1. First, save both scripts in the same directory:

    • Save the previous speed test script as speedtest.sh
    • Save this new setup script as setup.sh
  2. Make both scripts executable:

chmod +x setup.sh speedtest.sh
  1. Run the setup script with sudo:
sudo ./setup.sh

The setup script will:

  • Install necessary dependencies
  • Create required directories
  • Set up appropriate permissions
  • Install the speed test script
  • Configure the cron job based on your preference
  • Provide a summary of the installation

You’ll be prompted to choose how frequently you want to run the speed tests:

  1. Hourly (recommended)
  2. Every 30 minutes
  3. Every 15 minutes
  4. Daily

The script will automatically:

  • Install to /opt/speedtest-monitor
  • Set up logs in /var/log/speedtest
  • Configure the cron job with your chosen frequency
  • Set appropriate permissions

After installation, you can:

  • Check the logs in /var/log/speedtest/
  • Modify the cron schedule by running sudo crontab -e
  • Test the script manually by running /opt/speedtest-monitor/speedtest.sh

Currently working with ubuntu 24.04