Ubuntu 24.04 AutoPatch Script

Ubuntu 24.04 AutoPatch Script

Script Overview

This Ubuntu 24.04 AutoPatch script is designed to automate the process of updating your Ubuntu server’s packages, handling any packages that are kept back during the update process, and ensuring that the system is fully up to date. It also checks if a reboot is required after the updates and performs it automatically if necessary. The script is particularly useful for servers where you want to ensure that updates are applied regularly without manual intervention.

#!/bin/bash

# Define a file to track progress
PROGRESS_FILE="/var/log/update-script-progress"

# Function to check if a reboot is required
check_reboot() {
    if [ -f /var/run/reboot-required ]; then
        echo "Reboot required. Rebooting now..."
        echo "step1_reboot" > $PROGRESS_FILE
        reboot
        exit 0
    fi
}

# Function to check the progress and continue where left off
check_progress() {
    if [ -f $PROGRESS_FILE ]; then
        PROGRESS=$(cat $PROGRESS_FILE)
        case $PROGRESS in
            "step1_reboot")
                echo "Continuing after first reboot..."
                step2_install_updates
                ;;
            "step2_updates")
                echo "Continuing after updates..."
                step3_install_kept_back
                ;;
            "step3_kept_back")
                echo "Continuing after installing kept-back packages..."
                check_reboot_after_updates
                ;;
            *)
                echo "Unknown progress state, starting from the beginning."
                start_script
                ;;
        esac
    else
        start_script
    fi
}

# Function to start the script
start_script() {
    check_reboot
    step2_install_updates
}

# Function to perform updates
step2_install_updates() {
    echo "Updating package lists..."
    sudo apt update

    echo "Upgrading installed packages..."
    # Set non-interactive frontend to avoid prompts
    sudo DEBIAN_FRONTEND=noninteractive apt-get upgrade -y --with-new-pkgs

    echo "step2_updates" > $PROGRESS_FILE
    step3_install_kept_back
}

# Function to install kept-back packages
step3_install_kept_back() {
    echo "Installing kept-back packages..."
    # Install kept-back packages by explicitly listing them
    KEPT_BACK=$(apt list --upgradable 2>/dev/null | grep -P '^\S+' -o)
    if [ -n "$KEPT_BACK" ]; then
        sudo DEBIAN_FRONTEND=noninteractive apt-get install -y $KEPT_BACK
    fi

    echo "step3_kept_back" > $PROGRESS_FILE
    check_reboot_after_updates
}

# Function to check if a reboot is required after updates
check_reboot_after_updates() {
    check_reboot
    cleanup
}

# Function to clean up unnecessary packages
cleanup() {
    echo "Cleaning up unnecessary packages..."
    sudo apt autoremove -y
    sudo apt autoclean

    echo "System is up to date. No reboot required."
    rm -f $PROGRESS_FILE
}

# Start or continue the script
check_progress

Script Features

  1. Automatic Updates: The script automatically updates the package lists, upgrades installed packages, and installs any packages that are kept back during the upgrade process.
  2. Automatic Reboot: If a reboot is required after the updates (e.g., due to kernel updates), the script will automatically reboot the server.
  3. Progress Tracking: The script tracks its progress using a log file (/var/log/update-script-progress) to ensure that if it is interrupted (e.g., by a reboot), it can resume where it left off.
  4. Non-Interactive Operation: The script runs in non-interactive mode, making it ideal for automated or background execution without requiring manual input.

How the Script Works

  1. Check for Reboot Requirement: The script first checks if a reboot is already required (from a previous update) and reboots the system if necessary.
  2. Update and Upgrade Packages: It updates the package lists (apt update), upgrades the installed packages (apt-get upgrade --with-new-pkgs), and handles any held-back packages explicitly (apt-get install).
  3. Reboot if Needed: After the updates, the script checks again if a reboot is required and performs it automatically if necessary.
  4. Clean Up: The script cleans up unnecessary packages (apt autoremove, apt autoclean) to free up space.
  5. Progress Logging: The script logs its progress to ensure that it can continue from where it left off if interrupted.

How to Set Up the Script

Upload the Script: Save the provided script to a file on your server, for example, /opt/scripts/update-script.sh.

Make the Script Executable: Run the following command to make the script executable

sudo chmod +x /opt/scripts/update-script.sh

Schedule the Script: To run this script regularly, you can schedule it using cron. For example, to run the script every night at 2 AM, you can add the following line to your crontab:

sudo crontab -e

Then add:

# Run the script at 2 AM every day to ensure the system is updated
0 2 * * * /opt/scripts/update-script.sh >> /var/log/update-script.log 2>&1

# Run the script at system reboot to continue updates if the system was rebooted during an update
@reboot /opt/scripts/update-script.sh >> /var/log/update-script.log 2>&1

Daily 2 AM Job: This cron job is scheduled to run the script at 2 AM every day to perform regular updates.

Reboot Job: The @reboot cron job is crucial for ensuring that if the system was rebooted during an update (either automatically by the script or manually), the script will continue from where it left off. This helps maintain the integrity and continuity of the update process.

This setup ensures that your server stays updated both regularly and in cases where an update process is interrupted by a reboot.

Manual Execution: You can also run the script manually at any time by executing:

sudo /opt/scripts/update-script.sh

Additional Considerations

  • Logging: The script uses /var/log/update-script-progress to track progress and /var/log/update-script.log (in the cron setup) to log the output. You may want to monitor these logs to ensure the updates are running smoothly.
  • Permissions: Ensure the script has appropriate permissions to execute commands like apt-get and reboot, which may require sudo.
  • Testing: It’s a good idea to test the script manually first to ensure it works as expected before setting it up as a cron job.

This setup will keep your server updated automatically, minimizing the risk of security vulnerabilities and ensuring that you benefit from the latest features and fixes.

Packages up to date! - Ubuntu 24.04 autopatch script

Disclaimer

Before running any automated update scripts on your server, it is critical to ensure that you have a reliable backup system in place. Regularly backing up your server’s data is a best practice that can help you recover from unexpected issues.

The script provided is intended to automate the update process on a server, including handling reboot scenarios. While it has been designed to minimize disruptions and ensure that updates are applied correctly, running automated update scripts carries inherent risks.

By using this script, you acknowledge that you do so at your own risk. The creators and providers of this script hold no responsibility for any damage, data loss, or service interruptions that may occur as a result of running this script. It is strongly recommended that you maintain comprehensive backups before implementing this or any other automated processes on your system.