0% found this document useful (0 votes)
22 views4 pages

Essential Linux Automation Scripts

The document provides essential shell scripts for automating various Linux tasks, including backup, system updates, user account management, disk usage monitoring, service monitoring, log rotation, and server health checks. Each script is accompanied by a brief explanation of its purpose and functionality. Additionally, instructions for scheduling these scripts using cron are included.

Uploaded by

karan209205
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views4 pages

Essential Linux Automation Scripts

The document provides essential shell scripts for automating various Linux tasks, including backup, system updates, user account management, disk usage monitoring, service monitoring, log rotation, and server health checks. Each script is accompanied by a brief explanation of its purpose and functionality. Additionally, instructions for scheduling these scripts using cron are included.

Uploaded by

karan209205
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Md. Ikbal Hossain Mobile: 01950758712 E-mail: ikbalbd1052@gmail.

com

Mastering Linux Automation: Simplify Your Workflow with These Essential Shell Scripts.

1. Backup Automation Script

Automating backups is critical for data safety and disaster recovery.


Script: auto_backup.sh

#!/bin/bash

# Variables
SOURCE_DIR="/path/to/source"
BACKUP_DIR="/path/to/backup"
LOG_FILE="/var/log/[Link]"
DATE=$(date +"%Y-%m-%d_%H-%M-%S")

# Create a backup
echo "[$DATE] Starting backup..." >> "$LOG_FILE"
tar -czf "$BACKUP_DIR/backup_$[Link]" "$SOURCE_DIR" 2>>"$LOG_FILE"

if [ $? -eq 0 ]; then
echo "[$DATE] Backup completed successfully." >> "$LOG_FILE"
else
echo "[$DATE] Backup failed!" >> "$LOG_FILE"
fi

2. System Update Script

Keep all packages up to date to maintain security and performance.


Script: auto_update.sh

#!/bin/bash

LOG_FILE="/var/log/system_update.log"
DATE=$(date +"%Y-%m-%d_%H-%M-%S")

echo "[$DATE] Starting system update..." >> "$LOG_FILE"

# Update package lists and upgrade


sudo apt update && sudo apt upgrade -y >> "$LOG_FILE" 2>&1

if [ $? -eq 0 ]; then
echo "[$DATE] System update completed successfully." >> "$LOG_FILE"
else
echo "[$DATE] System update failed!" >> "$LOG_FILE"
fi

Page 1 of 4
Md. Ikbal Hossain Mobile: 01950758712 E-mail: ikbalbd1052@[Link]

3. User Account Management Script

Easily create and manage user accounts.


Script: user_management.sh

#!/bin/bash

# Add user
add_user() {
read -p "Enter username: " username
sudo adduser "$username"
echo "User $username added."
}

# Delete user
delete_user() {
read -p "Enter username to delete: " username
sudo deluser "$username"
echo "User $username deleted."
}

echo "1. Add User"


echo "2. Delete User"
read -p "Choose an option: " choice

case $choice in
1)
add_user
;;
2)
delete_user
;;
*)
echo "Invalid option!"
;;
esac

4. Disk Usage Monitoring Script

Monitor disk space and send alerts if it exceeds a threshold.


Script: disk_monitor.sh

#!/bin/bash

THRESHOLD=80
LOG_FILE="/var/log/disk_usage.log"
DATE=$(date +"%Y-%m-%d_%H-%M-%S")

echo "[$DATE] Checking disk usage..." >> "$LOG_FILE"

df -H | awk '{ print $5 " " $1 }' | while read output; do


usage=$(echo "$output" | awk '{print $1}' | sed 's/%//')

Page 2 of 4
Md. Ikbal Hossain Mobile: 01950758712 E-mail: ikbalbd1052@[Link]

filesystem=$(echo "$output" | awk '{print $2}')

if [ "$usage" -ge "$THRESHOLD" ]; then


echo "[$DATE] WARNING: $filesystem usage is at ${usage}%!" >> "$LOG_FILE"
fi
done

5. Service Monitor and Restart Script

Ensure essential services remain active.


Script: service_monitor.sh

#!/bin/bash

SERVICE_NAME="apache2"
LOG_FILE="/var/log/service_monitor.log"
DATE=$(date +"%Y-%m-%d_%H-%M-%S")

echo "[$DATE] Checking $SERVICE_NAME service..." >> "$LOG_FILE"

if systemctl is-active --quiet "$SERVICE_NAME"; then


echo "[$DATE] $SERVICE_NAME is running." >> "$LOG_FILE"
else
echo "[$DATE] $SERVICE_NAME is not running. Restarting..." >> "$LOG_FILE"
systemctl restart "$SERVICE_NAME"

if [ $? -eq 0 ]; then
echo "[$DATE] $SERVICE_NAME restarted successfully." >> "$LOG_FILE"
else
echo "[$DATE] Failed to restart $SERVICE_NAME." >> "$LOG_FILE"
fi
fi

6. Log Rotation Script

Automatically manage and rotate logs to save space.


Script: log_rotation.sh

#!/bin/bash

LOG_DIR="/var/log/myapp"
MAX_SIZE=10485760 # 10 MB
DATE=$(date +"%Y-%m-%d_%H-%M-%S")

for file in "$LOG_DIR"/*.log; do


if [ -f "$file" ]; then
size=$(stat -c%s "$file")
if [ "$size" -ge "$MAX_SIZE" ]; then
mv "$file" "${file}_$DATE"
gzip "${file}_$DATE"
echo "Rotated $file to ${file}_$[Link]"

Page 3 of 4
Md. Ikbal Hossain Mobile: 01950758712 E-mail: ikbalbd1052@[Link]

fi
fi
done

7. Automated Server Health Check Script

Consolidate health metrics like CPU, memory, and disk usage.


Script: health_check.sh

#!/bin/bash

DATE=$(date +"%Y-%m-%d_%H-%M-%S")
LOG_FILE="/var/log/server_health.log"

echo "[$DATE] Server Health Check:" >> "$LOG_FILE"


echo "CPU Load: $(uptime | awk -F'load average:' '{ print $2 }')" >> "$LOG_FILE"
echo "Memory Usage: $(free -h | grep Mem | awk '{print $3 "/" $2}')" >> "$LOG_FILE"
echo "Disk Usage: $(df -h / | awk 'NR==2 {print $5}')" >> "$LOG_FILE"
echo "-------------------------------" >> "$LOG_FILE"

8. Scheduled Job Automation (Cron Setup)

To schedule these scripts:

1. Edit crontab:

crontab -e

2. Add entries like:

0 2 * * * /path/to/auto_backup.sh
0 3 * * * /path/to/auto_update.sh

Page 4 of 4

Common questions

Powered by AI

Integrating these scripts into a comprehensive automation solution for a Linux server environment streamlines management tasks, improves security, and enhances operational efficiency. By combining backup automation, system updates, user account management, disk and service monitoring, log rotation, and health checks, administrators can ensure high availability, security, and performance of the server infrastructure. Furthermore, scheduling through cron ensures tasks are performed consistently, reducing manual oversight and making system management more resilient to errors and more capable of handling dynamic server demands .

Administrators might face challenges such as configuring scripts for specific environments, managing script dependencies, or ensuring appropriate user permissions for executing scripts and accessing system resources. These challenges can be addressed by customizing script variables to environment-specific settings, using package managers to handle dependencies, implementing thorough testing before deployment, and ensuring scripts have the necessary privileges through proper user account configurations and sudo settings. Additionally, setting up robust logging and alerts can aid in quickly identifying and resolving issues as they arise, ensuring smooth operations .

The health_check.sh script contributes to maintaining overall server health by regularly logging key metrics such as CPU load, memory usage, and disk usage. This information allows administrators to identify and address performance bottlenecks or resource shortages proactively. By providing a consolidated view of server health, administrators can make informed decisions about resource allocation, system scaling, and necessary optimizations to maintain efficient and robust server operations .

The system update script auto_update.sh enhances security and performance by automatically updating package lists and installing the latest available software updates. This process is crucial for addressing security vulnerabilities, supporting new features, and ensuring the system performs optimally. The script's exit status handling ensures updates are completed successfully or logs an error, facilitating troubleshooting .

Scheduling scripts with cron offers significant advantages in server administration by allowing tasks to be automated at defined intervals without human intervention. This ensures scripts such as auto_backup.sh and auto_update.sh run consistently and reliably at specified times, improving operational efficiency and freeing administrators to focus on more complex tasks. Additionally, it minimizes the risk of human error, provides consistency in task execution, and enhances system management by automating routine maintenance tasks .

The disk_monitor.sh script helps prevent system failures by continuously monitoring disk space usage and logging warnings when usage exceeds a specified threshold (80% by default). By alerting administrators to high disk usage, it allows proactive management of resources before they reach critical levels that could lead to system failures, data loss, or operational disruptions. This proactive approach ensures ongoing system stability and reliability .

The service_monitor.sh script can be used to ensure that mission-critical services, such as Apache2, remain operational by regularly checking their status. If a service is found not running, the script attempts to restart it and logs the outcome. This automated monitoring and restart functionality ensures that services necessary for business operations remain active, reducing downtime and preventing service disruptions .

Automating backup processes with scripts such as auto_backup.sh ensures consistent and timely data backups, which are crucial for data safety and disaster recovery. By using such scripts, organizations can minimize the risk of human error, ensure compliance with data retention policies, and reduce operational overhead. The script's use of logging via LOG_FILE ensures that all activities are documented for audit purposes .

User account management, as demonstrated by the user_management.sh script, is vital in Linux administration because it ensures only authorized users have access to system resources, thereby enhancing security. Managing user accounts efficiently helps in maintaining organizational policies on user permissions and accesses. Additionally, the script's interactive addition and deletion features allow administrators to easily manage user accounts without manual command-line inputs, reducing the likelihood of errors .

Log rotation, as implemented in log_rotation.sh, serves to manage and compress log files once they exceed a certain size (10 MB by default), preventing the accumulation of large log files that can consume disk space excessively. This process is necessary for system management because it ensures sufficient disk space remains available for other critical operations and maintains system performance. By automatically managing logs, administrators can prevent potential issues related to disk space shortages .

You might also like