Skip to content

Instantly share code, notes, and snippets.

@filipnet
Created November 17, 2024 17:48
Show Gist options
  • Select an option

  • Save filipnet/639d996a3753e9fe13acfa89f6617621 to your computer and use it in GitHub Desktop.

Select an option

Save filipnet/639d996a3753e9fe13acfa89f6617621 to your computer and use it in GitHub Desktop.
This script checks for available system updates, reports if a reboot is required, lists enabled repositories, and sends an email notification to specified recipients with the update details.
#!/bin/bash
# Configuration: Define recipients (space-separated emails)
RECIPIENTS="administrator@example.com"
# Constants
DASHES="##############################"
# Function: Check for updates
check_updates() {
dnf check-update --quiet | grep -v "^$"
}
# Function: Count updates
count_updates() {
echo "$1" | sed '/^\s*$/d' | wc -l
}
# Function: Check if a restart is required
check_restart() {
if ! needs-restarting -r &>/dev/null; then
echo "Reboot $(hostname) is required to update the kernel or core libraries."
else
echo ""
fi
}
# Function: Fetch enabled repositories
fetch_repositories() {
dnf repolist enabled -v | grep 'Repo-name' | sed -r 's/.{15}//'
}
# Function: Build the email report
build_report() {
local updates="$1"
local restart="$2"
local repos="$3"
local report="$DASHES\n# RESTART REQUIRED\n$DASHES\n"
if [[ -n $restart ]]; then
report+="$restart\n\n"
else
report+="No restart required.\n\n"
fi
report+="$DASHES\n# UPDATES AVAILABLE\n$DASHES\n"
report+="$updates\n\n"
report+="$DASHES\n# REPOSITORIES\n$DASHES\n"
report+="$repos\n"
echo -e "$report"
}
# Function: Send email to recipients
send_email() {
local subject="$1"
local body="$2"
for recipient in $RECIPIENTS; do
echo -e "$body" | mail -s "$subject" "$recipient"
done
}
# Main script execution
main() {
local updates=$(check_updates)
local updates_count=$(count_updates "$updates")
local restart_required=$(check_restart)
local repositories=$(fetch_repositories)
if [[ $updates_count -gt 0 ]]; then
local report=$(build_report "$updates" "$restart_required" "$repositories")
local subject="[WARNING] ${updates_count} Updates for $(hostname) available"
send_email "$subject" "$report"
fi
}
# Run the script
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment