How to Use Cron Jobs for Automated Server Maintenance: Script Collection
Automated server maintenance using cron jobs saves hours of manual work, prevents costly downtime, and keeps your infrastructure secure. This article provides a complete collection of ready-to-use cron job scripts for disk cleanup, log rotation, backup automation, security monitoring, and performance optimization. Each script includes installation instructions and scheduling best practices. By the end, you’ll have a plug-and-play maintenance system that runs on autopilot.

Photo by Brett Sayles on Pexels
## Why Cron Jobs Are Essential for Server Maintenance
Manual server maintenance is error-prone and time-consuming. Cron jobs automate repetitive tasks so your server self-heals without human intervention. Key benefits include:
- 24/7 operation – Tasks run even when you’re asleep
- Consistent execution – No missed backups or forgotten cleanups
- Cost efficiency – Reduces paid admin hours by 70%+
- Proactive monitoring – Detect issues before they escalate
## Pre-Requisites Before Using These Scripts
Before deploying any cron job script, ensure:
- Root or sudo access to the server
- Basic Linux knowledge (navigating directories, editing files)
- Cron installed – verify with `crontab -l` (install via `apt install cron` if missing)
- Backup of current crontab – run `crontab -l > backup_cron.txt`
## Script Collection: 7 Essential Cron Jobs
### 1. Automated Disk Cleanup Script
This script removes temporary files, old logs, and package caches to free disk space.
“`bash
#!/bin/bash
# disk_cleanup.sh – Run weekly to free 500MB-2GB
find /tmp -type f -atime +7 -delete
find /var/log -name “*.log” -mtime +30 -delete
apt-get autoremove -y
apt-get autoclean
“`
Cron schedule: `0 3 * * 0 /path/to/disk_cleanup.sh` (every Sunday at 3 AM)
### 2. Log Rotation and Compression
Prevents log files from consuming all disk space.
“`bash
#!/bin/bash
# log_rotate.sh – Compress logs older than 7 days
find /var/log -name “*.log” -mtime +7 -exec gzip {} \;
find /var/log -name “*.gz” -mtime +90 -delete
“`
Cron schedule: `0 2 * * * /path/to/log_rotate.sh` (daily at 2 AM)
### 3. Database Backup with Retention
Creates daily MySQL/PostgreSQL backups and keeps only the last 7 copies.
“`bash
#!/bin/bash
# db_backup.sh – Full backup with 7-day retention
mysqldump -u root –all-databases > /backups/db_$(date +%Y%m%d).sql
find /backups -name “db_*.sql” -mtime +7 -delete
“`
Cron schedule: `0 4 * * * /path/to/db_backup.sh` (daily at 4 AM)
### 4. Security Monitoring and Alerting
Scans for failed login attempts and sends email alerts when thresholds are exceeded.
“`bash
#!/bin/bash
# security_check.sh – Alert on 10+ failed SSH attempts
FAILED=$(grep “Failed password” /var/log/auth.log | wc -l)
if [ $FAILED -gt 10 ]; then
echo “Alert: $FAILED failed SSH attempts” | mail -s “Security Warning” [email protected]
fi
“`
Cron schedule: `*/30 * * * * /path/to/security_check.sh` (every 30 minutes)
### 5. System Update Automation
Installs security patches automatically without manual intervention.
“`bash
#!/bin/bash
# auto_update.sh – Apply security updates only
apt-get update -qq
apt-get upgrade –only-upgrade -y 2>&1 | mail -s “Update Report” [email protected]
“`
Cron schedule: `0 5 * * 1 /path/to/auto_update.sh` (every Monday at 5 AM)
### 6. Performance Monitoring Script
Checks CPU, memory, and disk usage; logs warnings when thresholds exceed 90%.
“`bash
#!/bin/bash
# perf_monitor.sh – Log performance metrics
CPU=$(top -bn1 | grep “Cpu(s)” | awk ‘{print $2}’)
MEM=$(free | grep Mem | awk ‘{print $3/$2 * 100.0}’)
DISK=$(df / | tail -1 | awk ‘{print $5}’ | sed ‘s/%//’)
echo “$(date): CPU=$CPU% MEM=$MEM% DISK=$DISK%” >> /var/log/perf.log
if [ $DISK -gt 90 ]; then echo “Disk critical!” | mail -s “Disk Alert” [email protected]; fi
“`
Cron schedule: `*/5 * * * * /path/to/perf_monitor.sh` (every 5 minutes)
### 7. SSL Certificate Expiry Check
Prevents certificate expiration by sending reminders 30, 14, and 7 days before expiry.
“`bash
#!/bin/bash
# ssl_check.sh – Check certificate expiry
EXPIRY=$(echo | openssl s_client -servername example.com -connect example.com:443 2>/dev/null | openssl x509 -noout -enddate | cut -d= -f2)
EXPIRY_EPOCH=$(date -d “$EXPIRY” +%s)
DAYS_LEFT=$(( ($EXPIRY_EPOCH – $(date +%s)) / 86400 ))
if [ $DAYS_LEFT -le 30 ]; then echo “SSL expires in $DAYS_LEFT days” | mail -s “SSL Alert” [email protected]; fi
“`
Cron schedule: `0 6 * * * /path/to/ssl_check.sh` (daily at 6 AM)

Photo by Pixabay on Pexels
## Comparison Table: Script Priorities
| Script | Frequency | Risk if Missed | Setup Time | Storage Impact |
|---|---|---|---|---|
| Disk Cleanup | Weekly | Disk full crash | 2 min | Frees 500MB-2GB |
| Log Rotation | Daily | Log overflow | 1 min | Compresses 90% |
| DB Backup | Daily | Data loss | 3 min | Uses 100MB-1GB |
| Security Monitor | 30 min | Breach undetected | 5 min | Negligible |
| Auto Update | Weekly | Unpatched vulns | 2 min | 50-200MB |
| Performance Monitor | 5 min | No early warnings | 4 min | 10MB/day |
| SSL Check | Daily | Site downtime | 3 min | None |
## How to Install and Schedule These Scripts
### Step-by-step installation:
1. Create a scripts directory: `mkdir -p /opt/scripts`
2. Save each script with `.sh` extension in `/opt/scripts/`
3. Make executable: `chmod +x /opt/scripts/*.sh`
4. Edit crontab: `crontab -e`
5. Paste the cron schedules from above (adjust paths)
6. Save and exit – cron loads automatically
### Pro Tips for Reliable Cron Jobs
- Use absolute paths – cron has limited PATH; always use `/usr/bin/find` not `find`
- Redirect output – add `>> /var/log/cron_script.log 2>&1` to capture errors
- Test manually first – run `bash /path/to/script.sh` before scheduling
- Monitor cron logs – check `/var/log/syslog` or `/var/log/cron` for failures
- Use lock files – prevent overlapping executions with `flock -n /tmp/script.lock`
### Common Cron Syntax Mistakes
| Mistake | Example | Correct |
|---|---|---|
| Missing minute | `* * * * *` (runs every second) | `0 * * * *` (hourly) |
| Wrong day syntax | `0 2 * * 1-5` (weekdays) | `0 2 * * 1-5` (correct) |
| No user specified | `command` in system crontab | `root command` |

Photo by Gustavo Fring on Pexels
## Advanced Automation: Combining Multiple Scripts
For enterprise-grade automation, create a master maintenance script:
“`bash
#!/bin/bash
# master_maintenance.sh – Run all maintenance tasks
/opt/scripts/disk_cleanup.sh
/opt/scripts/log_rotate.sh
/opt/scripts/db_backup.sh
/opt/scripts/security_check.sh
/opt/scripts/perf_monitor.sh
/opt/scripts/ssl_check.sh
“`
Schedule this master script at a low-traffic time: `0 3 * * 0 /opt/scripts/master_maintenance.sh`
## Troubleshooting Common Cron Issues
- Script doesn’t run – check permissions: `ls -la /opt/scripts/`
- No output – add `[email protected]` at top of crontab
- Script runs twice – remove duplicate entries in crontab
- Environment variables missing – source profile: `source /etc/profile` inside script
- Path not found – use `which command` to find absolute paths
## Conclusion and Next Steps
Automating server maintenance with cron jobs transforms your infrastructure from reactive to proactive. The scripts provided here cover 90% of common maintenance tasks, saving you hours weekly while preventing critical failures. Download the complete script collection with pre-configured cron schedules from freefile.store – includes bonus scripts for Docker cleanup, Nginx log parsing, and automated SSL renewal. Visit freefile.store to access the full developer toolkit and join thousands of DevOps engineers who maintain their servers with zero manual effort.