Created
February 6, 2025 13:08
-
-
Save BakirGracic/24ae99dc4f6ebf466f187fa889b27b3c to your computer and use it in GitHub Desktop.
Linux server APT pkg update cron shell script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Set variables | |
LOG_FILE="/root/SERVER_SUSTAINABILITY/maintenance.log" | |
HOSTNAME=$(hostname) | |
log() { | |
echo "$(date +"%Y-%m-%d %H:%M:%S") $1" | touch -a "$LOG_FILE" | |
} | |
# Ensure the script is run as root | |
if [ "$EUID" -ne 0 ]; then | |
log "ERROR: This script must be run as root!" | |
exit 1 | |
fi | |
log "----- Starting System Maintenance -----" | |
# Update package lists | |
log "Updating package lists..." | |
if apt update -y >>"$LOG_FILE" 2>&1; then | |
log "Package lists updated successfully." | |
else | |
log "ERROR: Failed to update package lists!" | |
echo "System maintenance failed on $HOSTNAME. Check logs: $LOG_FILE" | |
exit 1 | |
fi | |
# Upgrade installed packages | |
log "Upgrading packages..." | |
if apt full-upgrade -y >>"$LOG_FILE" 2>&1; then | |
log "Packages upgraded successfully." | |
else | |
log "ERROR: Failed to upgrade packages!" | |
echo "System maintenance failed on $HOSTNAME. Check logs: $LOG_FILE" | |
exit 1 | |
fi | |
# Remove unused dependencies | |
log "Removing unnecessary packages..." | |
if apt autoremove -y >>"$LOG_FILE" 2>&1; then | |
log "Unused packages removed." | |
else | |
log "ERROR: Failed to remove unnecessary packages!" | |
fi | |
# Clean up APT cache | |
log "Cleaning up APT cache..." | |
if apt clean >>"$LOG_FILE" 2>&1; then | |
log "APT cache cleaned." | |
else | |
log "ERROR: Failed to clean APT cache!" | |
fi | |
# Check if a reboot is needed | |
if [ -f /var/run/reboot-required ]; then | |
log "Reboot required. Rebooting now..." | |
echo "System maintenance completed on $HOSTNAME. Rebooting server." | |
shutdown -r now | |
else | |
log "No reboot required." | |
echo "System maintenance completed on $HOSTNAME. No reboot needed." | |
fi | |
log "----- Maintenance Completed -----\n\n" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment