Bash Scripts Every Server Admin Home lab users Should Automate

1. Automating System Updates

Regularly updating system packages is critical for maintaining security and performance. This script automates the update and upgrade process.

#!/bin/bash
# Update and upgrade system packages
echo "Starting system update..."
sudo apt update && sudo apt upgrade -y
echo "System update completed."

- This script updates the package lists and upgrades installed packages without manual intervention. - The `-y` flag automatically confirms the upgrade prompts.

2. Disk Usage Monitoring Script

Monitoring disk usage prevents systems from running out of space, which can cause major disruptions.

#!/bin/bash
# Check disk usage and send alert if usage exceeds 80%
THRESHOLD=80
df -h | awk '{ if($5+0 > THRESHOLD) print $0; }' | while read output;
do
    echo "Disk usage alert: $output"
done

- The script checks if any partition exceeds 80% disk usage and prints a warning. - You can modify it to send an email alert using `mail` or `sendmail`.

3. Automated Backup Script

This script creates automated backups of important directories, ensuring data is always protected.

#!/bin/bash
# Backup a directory and store it in a backup folder with a timestamp
SOURCE="/path/to/important/data"
DEST="/path/to/backup/location"
TIMESTAMP=$(date +"%Y%m%d%H%M%S")
tar -czvf $DEST/backup_$TIMESTAMP.tar.gz $SOURCE
echo "Backup completed: $DEST/backup_$TIMESTAMP.tar.gz"

- This script compresses the specified directory into a `.tar.gz` file and saves it with a timestamp. - Ideal for scheduling backups via cron jobs.

4. Log Rotation Script

Logs can grow large and take up valuable disk space. This script rotates and compresses log files.

#!/bin/bash
# Rotate and compress logs
LOG_FILE="/path/to/logfile.log"
BACKUP_DIR="/path/to/log/backup"
TIMESTAMP=$(date +"%Y%m%d")
mv $LOG_FILE $BACKUP_DIR/log_$TIMESTAMP.log
gzip $BACKUP_DIR/log_$TIMESTAMP.log
touch $LOG_FILE
echo "Log rotation completed."

- Moves the current log to a backup directory, compresses it, and creates a new log file. - Keeps logs manageable in size.

5. Automated SSH Key Setup

This script simplifies the process of setting up SSH keys for remote login, improving security and automation.

#!/bin/bash
# Generate SSH key and copy to remote server
ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -q -N ""
ssh-copy-id user@remote_server
echo "SSH key setup completed."

- Generates an RSA key pair and copies the public key to the remote server for passwordless authentication.

6. Automated MySQL Database Backup

Backups are critical for database management. This script automates the process of dumping MySQL databases.

#!/bin/bash
# MySQL database backup
DB_NAME="my_database"
USER="db_user" 
PASSWORD="db_pass"
BACKUP_DIR="/path/to/backup"
TIMESTAMP=$(date +"%Y%m%d%H%M%S")
mysqldump -u $USER -p$PASSWORD $DB_NAME > $BACKUP_DIR/${DB_NAME}_$TIMESTAMP.sql
echo "Database backup completed: $BACKUP_DIR/${DB_NAME}_$TIMESTAMP.sql"

- This script uses `mysqldump` to create a backup of a MySQL database and stores it with a timestamp. - Regular backups ensure data recovery in case of failure.

7. Automated Docker Cleanup

Docker containers, images, and volumes can accumulate over time, consuming disk space. This script automates cleanup.

#!/bin/bash
# Docker container and image cleanup
docker system prune -af
docker volume prune -f
echo "Docker cleanup completed."

- This script removes all stopped containers, unused networks, dangling images, and volumes. - Helps maintain a clean Docker environment.

8. Kubernetes Pod Status Check

This script monitors Kubernetes pods to ensure your application is running as expected.

#!/bin/bash
# Check Kubernetes pod status
NAMESPACE="default"
kubectl get pods -n $NAMESPACE

- This script uses `kubectl` to fetch and display the status of all pods in a given namespace. - Can be used to monitor application health in Kubernetes clusters.

9. SSL Certificate Expiry Checker

SSL certificates need to be renewed periodically. This script checks when your SSL certificate expires and alerts you in advance.

#!/bin/bash
# Check SSL certificate expiration 
DOMAIN="example.com"
EXPIRY_DATE=$(echo | openssl s_client -servername $DOMAIN -connect $DOMAIN:443 2>/dev/null | openssl x509 -noout -dates | grep notAfter | cut -d= -f2)
DAYS_LEFT=$(( ($(date -d "$EXPIRY_DATE" +%s) - $(date +%s)) / 86400 ))
echo "SSL certificate for $DOMAIN expires in $DAYS_LEFT days."

- Retrieves the SSL certificate for the specified domain and calculates how many days are left until it expires.

10. Git Auto Pull Script

For automated deployment processes, this script ensures the latest code from the repository is pulled to the server.

#!/bin/bash
# Auto pull the latest code from the Git repository
REPO_PATH="/path/to/repo"
BRANCH="main"
cd $REPO_PATH
git pull origin $BRANCH
echo "Code pulled from $BRANCH branch."

- Navigates to the repository directory and pulls the latest changes from the specified branch. - Useful for automating code deployment.

11. User Account Management Script

Managing user accounts is a common task for DevOps engineers. This script automates adding users to the system.

#!/bin/bash
# Add a new user
USERNAME=$1
sudo useradd -m $USERNAME 
sudo passwd $USERNAME
sudo usermod -aG sudo $USERNAME
echo "User $USERNAME added and granted sudo privileges."

- The script adds a new user, sets their password, and grants them sudo privileges. - Simplifies user account management on Linux systems.

12. Service Status Checker

Monitoring the status of critical services is essential for system reliability. This script automates service health checks.

#!/bin/bash
# Check the status of a specific service 
SERVICE=$1
systemctl is-active --quiet $SERVICE && echo "$SERVICE is running" || echo "$SERVICE is not running"

- Checks if a specified service is active and running, then prints the status. - Can be expanded to automatically restart the service if it’s not running.

By integrating these scripts into your daily operations, you can save time and ensure your infrastructure stays secure and efficient.

These scripts are awesome. I just used the docker cleanup one, cleaned up 12 gbs. Had no idea I that they were even there. Thank you.

1 Like

So I was curious to know is there a way in the Automated Docker Cleanup to not delete stopped containers?

When I ran it I totally forgot that I had several containers stopped and just had to repull the images.

Just remove the a argument in commands.

1 Like