DevOps工程师都应该自动化的 12 个 Bash 脚本

2024/11/22 11:00
阅读数 30

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.

-y 标志自动确认升级提示。


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.

该脚本检查任何分区是否超过 80% 的磁盘使用率并打印警告。您可以修改它以使用“mail”或“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.

该脚本将指定目录压缩为 .tar.gz 文件并使用时间戳保存。非常适合通过 cron 作业安排备份。


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 自动化ssh配置

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

该脚本简化了设置远程登录 SSH 密钥的过程,提高了安全性和自动化程度。

#!/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.

生成 RSA 密钥对并将公钥复制到远程服务器进行无密码身份验证。


6. Automated MySQL Database Backup 自动化数据库备份

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

备份对于数据库管理至关重要。此脚本可自动执行转储 MySQL 数据库的过程。

#!/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.

该脚本使用“mysqldump”创建 MySQL 数据库的备份并将其与时间戳一起存储。定期备份可确保在发生故障时恢复数据。

7. Automated Docker Cleanup 自动Docker清理

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

Docker 容器、镜像和卷会随着时间的推移而累积,从而占用磁盘空间。此脚本可自动清理。

#!/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.

此脚本删除所有已停止的容器、未使用的网络、悬空的图像和卷。有助于维护干净的 Docker 环境。


8. Kubernetes Pod Status Check 状态检查Pod

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

该脚本监视 Kubernetes pod以确保您的应用程序按预期运行。


#!/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.

该脚本使用“kubectl”来获取并显示给定命名空间中所有 pod 的状态。可用于监控 Kubernetes 集群中的应用程序健康状况。


9. SSL Certificate Expiry Checker SSL证书检查

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

SSL 证书需要定期更新。此脚本会检查您的 SSL 证书何时到期并提前提醒您。

#!/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.

检索指定域的 SSL 证书并计算其还剩多少天到期。


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.

管理用户帐户是 DevOps 工程师的常见任务。此脚本可自动将用户添加到系统。

#!/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.

该脚本添加新用户,设置其密码并授予他们 sudo 权限。简化 Linux 系统上的用户帐户管理。

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.


原文链接:https://blog.devops.dev/12-bash-scripts-every-devops-engineer-should-automate-5b954bbee24c 《12 Bash Scripts Every DevOps Engineer Should Automate》


本文分享自微信公众号 - DevOps云学堂(idevopsvip)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部