来自公众号:入门小站
当谈论一线运维工作中的常用 Shell 脚本时,以下是一些实用的例子:
uptime
命令和条件语句来实现。#!/bin/bash
threshold=1.0
load=$(uptime | awk -F'[, ]+' '{print $(NF-2)}')
if (( $(echo "$load > $threshold" | bc -l) )); then
echo "系统负载过高: $load" | mail -s "系统负载警报" [email protected]
fi
cp
命令和 cron
作业调度程序来完成。#!/bin/bash
backup_dir="/path/to/backup"
source_dir="/path/to/source"
timestamp=$(date +%Y%m%d%H%M%S)
backup_file="backup_$timestamp.tar.gz"
tar czf "$backup_dir/$backup_file" "$source_dir"
find
命令和条件语句来实现。#!/bin/bash
log_dir="/path/to/logs"
days_to_keep=7
find "$log_dir" -type f -name "*.log" -mtime +$days_to_keep -delete
systemctl
命令和条件语句来实现。#!/bin/bash
service_name="nginx"
if ! systemctl is-active --quiet "$service_name"; then
echo "服务 $service_name 未运行" | mail -s "服务状态警报" [email protected]
fi
rsync
命令和循环结构来实现。#!/bin/bash
servers=("server1" "server2" "server3")
source_dir="/path/to/source"
destination_dir="/path/to/destination"
for server in "${servers[@]}"; do
rsync -avz "$source_dir" "$server:$destination_dir"
done
df
命令和条件语句来实现。#!/bin/bash
threshold=90
df_output=$(df -h)
while read -r line; do
usage=$(echo "$line" | awk '{print $5}' | sed 's/%//')
if (( usage > threshold )); then
echo "磁盘空间不足: $line" | mail -s "磁盘空间警报" [email protected]
fi
done <<< "$df_output"
find
命令和条件语句来实现。#!/bin/bash
temp_dir="/path/to/temp"
expiration_days=3
find "$temp_dir" -type f -mtime +$expiration_days -delete
ping
命令和条件语句来实现。#!/bin/bash
service_ip="192.168.0.1"
if ! ping -c 1 -W 1 "$service_ip" > /dev/null; then
echo "无法访问服务: $service_ip" | mail -s "网络连通性警报" [email protected]
fi
mv
命令来实现。#!/bin/bash
directory="/path/to/files"
prefix="new_file"
count=1
for file in "$directory"/*; do
new_file_name="$directory/$prefix$count"
mv "$file" "$new_file_name"
((count++))
done
systemctl
命令和循环结构来实现。#!/bin/bash
services=("service1" "service2" "service3")
action="start" # 或者 "stop"
for service in "${services[@]}"; do
systemctl "$action" "$service"
done
这些例子只是一些常用的 Shell 脚本示例,实际的运维工作中可能会有更多不同的需求。根据具体的情况,可以自行修改和扩展这些脚本。