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

Essential Linux Shell Scripts Guide

Uploaded by

remenif437
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 views10 pages

Essential Linux Shell Scripts Guide

Uploaded by

remenif437
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

Linux Production Shell Scripts

1. File Backup Script:


#!/bin/bash

backup_dir="/path/to/backup"
source_dir="/path/to/source"

# Create a timestamped backup of the source directory


tar -czf "$backup_dir/backup_$(date +%Y%m%d_%H%M%S).[Link]"
"$source_dir"

2. System Monitoring Script:


#!/bin/bash

threshold=90

# Monitor CPU usage and trigger alert if threshold exceeded


cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d. -f1)
if [ "$cpu_usage" -gt "$threshold" ]; then
echo "High CPU usage detected: $cpu_usage%"
# Add alert/notification logic here
fi

3. User Account Management Script:


#!/bin/bash

username="newuser"

# Check if user exists; if not, create new user


if id "$username" &>/dev/null; then
echo "User $username already exists."
else
useradd -m "$username"
echo "User $username created."
Fi

4. Log Analyzer Script:


#!/bin/bash

logfile="/path/to/[Link]"

# Extract lines with "ERROR" from the log file


grep "ERROR" "$logfile" > error_log.txt
echo "Error log created."

5. Password Generator Script:


#!/bin/bash

length=12

# Generate a random password


password=$(openssl rand -base64 $length)
echo "Generated password: $password"

6. File Encryption/Decryption Script:


#!/bin/bash

file="/path/to/[Link]"

# Encrypt file using AES-256-CBC


openssl enc -aes-256-cbc -salt -in "$file" -out "$[Link]"
echo "File encrypted: $[Link]"

7. Automated Software Installation Script:


#!/bin/bash

packages=("package1" "package2" "package3")


# Install listed packages using apt-get
for package in "${packages[@]}"; do
sudo apt-get install "$package" -y
done

echo "Packages installed successfully."

8. Network Connectivity Checker Script:


#!/bin/bash

host="[Link]"

# Check network connectivity by pinging a host


if ping -c 1 "$host" &>/dev/null; then
echo "Network is up."
else
echo "Network is down."
fi

9. Website Uptime Checker Script:


#!/bin/bash

website="[Link]

# Check if website is accessible


if curl --output /dev/null --silent --head --fail "$website"; then
echo "Website is up."
else
echo "Website is down."
fi

10. Data Cleanup Script:


#!/bin/bash

directory="/path/to/cleanup"
# Remove files older than 7 days in specified directory
find "$directory" -type f -mtime +7 -exec rm {} \;
echo "Old files removed."

11. CPU Usage Tracker Script:


#!/bin/bash

output_file="cpu_usage_log.txt"

# Log current CPU usage to a file with timestamp


echo "$(date) $(top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | cut -d.
-f1)%" >> "$output_file"
echo "CPU usage logged."

12. System Information Script:


#!/bin/bash

output_file="system_info.txt"

# Gather system information and save to a file


echo "System Information:" > "$output_file"
echo "-------------------" >> "$output_file"
echo "Hostname: $(hostname)" >> "$output_file"
echo "OS: $(uname -a)" >> "$output_file"
echo "Memory: $(free -h)" >> "$output_file"
echo "Disk Space: $(df -h)" >> "$output_file"
echo "System info saved to $output_file."

13. Task Scheduler Script:


#!/bin/bash

scheduled_task="/path/to/your_script.sh"
schedule_time="0 2 * * *"
# Schedule a task using cron
echo "$schedule_time $scheduled_task" | crontab -
echo "Task scheduled successfully."

14. Disk Space Monitoring Script:


#!/bin/bash

threshold=90

# Monitor disk usage and trigger alert if threshold exceeded


disk_usage=$(df -h | grep "/dev/sda1" | awk '{print $5}' | cut -d%
-f1)
if [ "$disk_usage" -gt "$threshold" ]; then
echo "High disk usage detected: $disk_usage%"
# Add alert/notification logic here
fi

15. Remote Server Backup Script:


#!/bin/bash

source_dir="/path/to/source"
remote_server="user@remoteserver:/path/to/backup"

# Backup files/directories to a remote server using rsync


rsync -avz "$source_dir" "$remote_server"
echo "Files backed up to remote server."

16. Environment Setup Script:


#!/bin/bash

# Customize for your specific environment setup


echo "Setting up development environment..."
# Install necessary packages, configure settings, etc.
echo "Development environment set up successfully."
17. File Compression/Decompression Script:
#!/bin/bash

file_to_compress="/path/to/[Link]"

# Compress a file using gzip


gzip "$file_to_compress"
echo "File compressed: $file_to_compress.gz"

18. Database Backup Script:


#!/bin/bash

database_name="your_database"
output_file="database_backup_$(date +%Y%m%d).sql"

# Perform database backup using mysqldump


mysqldump -u username -ppassword "$database_name" > "$output_file"
echo "Database backup created: $output_file"

19. Git Repository Updater Script:


#!/bin/bash

git_repo="/path/to/your/repo"

# Update a Git repository


cd "$git_repo"
git pull origin master
echo "Git repository updated."

20. Directory Synchronization Script:


#!/bin/bash

source_dir="/path/to/source"
destination_dir="/path/to/destination"
# Synchronize directories using rsync
rsync -avz "$source_dir" "$destination_dir"
echo "Directories synchronized successfully."

21. Web Server Log Analyzer Script:


#!/bin/bash

log_file="/var/log/apache2/[Link]"

# Analyze web server log to count unique IP addresses


awk '{print $1}' "$log_file" | sort | uniq -c | sort -nr
echo "Web server log analyzed."

22. System Health Check Script:


#!/bin/bash

output_file="system_health_check.txt"

# Perform system health check and save results to a file


echo "System Health Check:" > "$output_file"
echo "---------------------" >> "$output_file"
echo "Uptime: $(uptime)" >> "$output_file"
echo "Load Average: $(cat /proc/loadavg)" >> "$output_file"
echo "Memory Usage: $(free -m)" >> "$output_file"
echo "System health check results saved to $output_file."

23. Automated Database Cleanup Script:


#!/bin/bash

database_name="your_database"
days_to_keep=7

# Clean up old database backups older than specified days


find /path/to/database/backups -name "$database_name*.sql" -mtime
+"$days_to_keep" -exec rm {} \;
echo "Old database backups cleaned up."
24. User Password Expiry Checker Script:
#!/bin/bash

# Check password expiry for users with bash shell


IFS=$'\n'
for user in $(cat /etc/passwd | grep "/bin/bash" | cut -d: -f1); do
password_expires=$(chage -l "$user" | grep "Password expires" |
awk '{print $4}')
echo "User: $user, Password Expires: $password_expires"
done
unset IFS

25. Service Restart Script:


#!/bin/bash

service_name="your_service"

# Restart a specified service


sudo systemctl restart "$service_name"
echo "Service $service_name restarted."

26. Folder Size Checker Script:


#!/bin/bash

folder_path="/path/to/folder"

# Check and display the size of a specified folder


du -sh "$folder_path"
echo "Folder size checked."

27. Backup Rotation Script:


#!/bin/bash

backup_dir="/path/to/backups"
max_backups=5

# Rotate backups by deleting the oldest if more than max_backups


while [ $(ls -1 "$backup_dir" | wc -l) -gt "$max_backups" ]; do
oldest_backup=$(ls -1t "$backup_dir" | tail -n 1)
rm -r "$backup_dir/$oldest_backup"
done
echo "Backup rotation completed."

28. Remote Script Execution Script:


#!/bin/bash

remote_server="user@remote-server"
remote_script="/path/to/remote/[Link]"

# Execute a script on a remote server via SSH


ssh "$remote_server" "bash -s" < "$remote_script"
echo "Remote script executed."

29. Network Interface Information Script:


#!/bin/bash

network_interface="eth0"

# Display network interface information


ifconfig "$network_interface"
echo "Network interface information displayed."

30. Random Quotes Generator Script:


#!/bin/bash

quotes=("Quote 1" "Quote 2" "Quote 3" "Quote 4")

# Generate and display a random quote from the array


random_index=$((RANDOM % ${#quotes[@]}))
echo "Random Quote: ${quotes[$random_index]}"

Common questions

Powered by AI

Logging in a CPU usage tracker script plays a critical role in recording system performance data over time, which is essential for identifying usage patterns, diagnosing issues, and planning resource allocation. Efficient management of logs involves rotating logs to prevent filesystem overflow and implementing archiving strategies to store historical data. Time-based log rotation and compression can reduce storage overhead, while analyzing log data can inform decisions on upgrading resources, adjusting scheduling, or identifying anomalies related to CPU abuse or inefficiency.

An environment setup script significantly improves workflows in multi-project development environments by automating the installation and configuration of project dependencies, reducing setup time, and minimizing human error. It ensures consistency across development environments by providing standardized setups, which is critical when team members work on multiple projects simultaneously. This uniformity allows developers to switch contexts more efficiently. Additionally, in environments where frequent onboarding or machine replacements occur, a setup script expedites the process, allowing developers to begin productive work faster.

Security considerations for a user account management script include ensuring strong passwords are set either programmatically or by enforcing the user to set them upon first login. The script should verify existing user accounts to prevent overwriting or unauthorized access. It should also enforce secure default group memberships and set appropriate file/directory permissions. Auditing and logging operations for compliance and ensuring encrypted transmission of any sensitive data during the account creation process are also critical. Additionally, integrating the script with LDAP or Kerberos for centralized authentication can further enhance security.

A file backup script can be made more efficient by using multiple processes to handle different parts of the backup concurrently. Tools like GNU Parallel or xargs can divide the backup task into smaller jobs that run concurrently, reducing the total time required for the backup process. Additionally, implementing a check for file modification times can ensure only newly changed files are backed up, further increasing efficiency. Using incremental backups instead of full backups whenever possible can also optimize this script.

AES-256-CBC is chosen for its high level of encryption security and widespread acceptance as a standard in securing sensitive data. Its advantage lies in its 256-bit key size, offering robust security against brute force attacks. However, its limitations include potential vulnerabilities to padding oracle attacks if proper padding is not implemented, and its requirement for a secure key management process. Additionally, performance might be a concern with large data sets, as symmetrical encryption can be resource-intensive.

Cron ensures successful automated execution of backup rotation scripts by allowing scheduling at consistent intervals, which can automatically manage and rotate backups without human intervention. By providing predictable execution patterns, cron minimizes the risks of human error, ensuring that backup files are rotated and old files deleted before they consume excessive storage space. It allows administrators to set specific execution times, avoiding system peak loads, and ensures that the retention policies are consistently applied, thus maintaining an orderly and manageable backup system.

Using grep for log analysis is straightforward but may face scalability issues with very large log files due to increased processing time and memory usage. As file sizes grow, grep may take longer to parse and extract data, and its lack of parallel processing capabilities limits the speed of operation. Accuracy can be affected by grep's simple pattern matching, which may not detect context-specific or multi-line log entries accurately compared to more sophisticated parsers. For large files or complex analysis, tools like awk, sed, or dedicated log management tools (such as ELK stack) offer better efficiency and feature-rich analysis capabilities.

Using 'rsync' in remote server backups offers distinct benefits over methods like FTP or SCP by providing efficient incremental file transfers, where only changed files or differences within files are transferred. This optimizes bandwidth usage and accelerates backup tasks, particularly over limited bandwidth connections. Rsync includes built-in compression and handles interrupted transfers robustly, allowing resumable operations. It also preserves file permissions and timestamps, thus maintaining data integrity more efficiently. In contrast, SCP and FTP do not natively support such granular synchronization or resume functionality.

A network connectivity checker script is preferred when the primary concern is the status of the local network or the connection to a particular host, such as when diagnosing local network issues or ensuring a server remains reachable. In contrast, a website uptime checker script is more suitable when monitoring the availability of a specific web service or site from an external perspective, where HTTP response statuses and web-specific issues (like DNS, TLS, or web server configurations) are more pertinent.

Scheduling tasks using cron impacts system performance and reliability by ensuring regular task execution without requiring manual intervention. It enhances reliability by maintaining consistency in task execution schedules. However, poorly configured cron jobs can lead to performance degradation, especially if resource-intensive tasks are scheduled simultaneously or at peak usage times. Additionally, creating log and output files without clear management can consume disk space, impacting performance. Properly optimizing these jobs by staggering execution times and monitoring system load can mitigate negative impacts while leveraging cron's scheduling strengths.

You might also like