https://mp.weixin.qq.com/s/ndFzJOCDRqUx_kxuc-mSkg

运维工作中,Shell 脚本是非常强大的工具,可以帮助自动化执行各种任务。以下是42个实用的Shell脚本示例,这些脚本可以直接或稍作修改后用于实际运维工作中,供参考。

  1. 检查磁盘空间
#!/bin/bash
df-h | grep -vE '^Filesystem|tmpfs|cdrom'| awk '{ print $5 " " $6 }'|whileread output;
do
echo$output
if[ $(echo$output| awk '{print $1}'| sed 's/%//g')-ge 80];then
echo"Warning: $output"
fi
done
  1. 监控系统负载
#!/bin/bash
uptime | awk -F 'load average:' '{print $2}' | sed 's/,//g'
  1. 查找并删除特定大小的文件
#!/bin/bash
find /path/to/search -type f -size +100M -exec rm -f {} \;
  1. 列出并杀死特定名称的进程
#!/bin/bash
ps aux | grep 'process_name' | awk '{print $2}' | xargs kill
  1. 监控特定端口的占用情况
#!/bin/bash
lsof -i :80
  1. 压缩目录
#!/bin/bash
tar -czvf archive_name.tar.gz /path/to/directory
  1. 解压文件
#!/bin/bash
tar -xzvf file_name.tar.gz
  1. 批量重命名文件
#!/bin/bash
for file in *.jpg; do
  mv "$file" "${file%.jpg}_renamed.jpg"
done
  1. 检查服务状态
#!/bin/bash
systemctl status nginx
  1. 重启服务
#!/bin/bash
systemctl restart nginx
  1. 备份MySQL数据库
#!/bin/bash
mysqldump -u root -p database_name > backup_file.sql
  1. 检查网络连接
#!/bin/bash
ping -c 4 google.com
  1. 更新系统
#!/bin/bash
apt-get update && apt-get upgrade -y

或对于基于RPM的系统:

#!/bin/bash
yum update -y
  1. 清理系统日志
#!/bin/bash
find /var/log/ -type f -mtime +30 -exec rm -f {} \;
  1. 监控CPU使用率
#!/bin/bash
top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}'
  1. 列出空目录
#!/bin/bash
find /path/to/search -type d -empty
  1. 监控内存使用情况
#!/bin/bash
free -m | grep Mem | awk '{print "Memory Usage: " $3/$2 * 100 "% Used, " $3/2 " GB Used, " $2/2 " GB Total"}'
  1. 重启系统
#!/bin/bash
reboot1
  1. 关闭系统
#!/bin/bash
shutdown -h now
  1. 检查SSH端口是否开放
#!/bin/bash
nc -zv localhost 22
  1. 监控并自动重启失败的服务
#!/bin/bash
SERVICE="myapp"
whiletrue;do
if! systemctl is-active --quiet $SERVICE;then
echo"Service $SERVICE is down, attempting to restart."
        systemctl restart $SERVICE
sleep10
else
echo"Service $SERVICE is running."
sleep60
fi
done
  1. 备份MySQL数据库并压缩
#!/bin/bash
DB_NAME="mydatabase"
DB_USER="root"
DB_PASS="mypassword"
BACKUP_DIR="/backups"
DATE=$(date +%Y-%m-%d_%H%M%S)
FILENAME="$BACKUP_DIR/$DB_NAME-$DATE.sql.gz"
mysqldump -u$DB_USER -p$DB_PASS $DB_NAME | gzip > $FILENAME
echo "Database backup completed: $FILENAME"
  1. 检查并删除旧文件
#!/bin/bash
find /path/to/files -type f -mtime +30 -exec rm {} \;
echo "Deleted files older than 30 days."
  1. 分析日志文件并发送报警邮件
#!/bin/bash
ERROR_COUNT=$(grep -c "ERROR" /var/log/myapp.log)
if [ $ERROR_COUNT -gt 0 ]; then
    echo "Detected $ERROR_COUNT errors in the log file." | mail -s "Error Alert" admin@example.com
fi
  1. 动态生成SSH密钥对
#!/bin/bash
KEY_DIR="/home/user/.ssh"
KEY_NAME="mykey"
mkdir -p $KEY_DIR
ssh-keygen -t rsa -b 4096 -f $KEY_DIR/$KEY_NAME -N ""
echo "SSH key pair generated at $KEY_DIR/$KEY_NAME"
  1. 批量更改文件扩展名
#!/bin/bash
for file in *.txt; do
    mv "$file" "${file%.txt}.md"
done
echo "File extensions changed from .txt to .md"
  1. 定时轮询API并处理响应
#!/bin/bash
whiletrue;do
    RESPONSE=$(curl -s http://api.example.com/data)
    process_response "$RESPONSE"
sleep60
done

process_response(){
# Process the response here
echo"$1"
}
  1. 检查磁盘空间并自动清理临时文件
#!/bin/bash
FREE_SPACE=$(df/| grep /| awk '{print $5}'| sed 's/%//g')
if[$FREE_SPACE-le 10];then
echo"Low disk space, cleaning up temporary files..."
rm-rf /tmp/*
echo"Temporary files cleaned up."
fi
  1. 自动化部署脚本
#!/bin/bash
# 假设使用Git进行版本控制
git pull
# 构建项目(示例:使用Maven)
mvn clean install
# 停止当前运行的服务
systemctl stop myapp
# 部署新构建的应用
cp target/myapp.jar /var/lib/myapp/
# 重启服务
systemctl start myapp
echo "Deployment completed successfully."
  1. 使用awk处理CSV文件
#!/bin/bash
awk -F, '{if ($1=="John Doe") print $2}' input.csv
  1. 批量更改多个文件的权限
#!/bin/bash
for file in /path/to/files/*; do
    chmod 644 "$file"
done
echo "Permissions updated for all files in /path/to/files/"
  1. 使用curl和jq处理JSON API响应
#!/bin/bash
response=$(curl -s https://api.example.com/data)
echo "$response" | jq '.items[].name'
  1. 监控网络带宽使用情况
#!/bin/bash
ifconfig eth0 | grep 'RX bytes' | awk '{print $2 $3}' | cut -d: -f2 | sed 's/ //g'
ifconfig eth0 | grep 'TX bytes' | awk '{print $2 $3}' | cut -d: -f2 | sed 's/ //g'
  1. 递归地搜索并替换文件中的文本
#!/bin/bash
find /path/to/search -type f -exec sed -i 's/old_text/new_text/g' {} +
echo "All occurrences of 'old_text' replaced with 'new_text'."
  1. 使用diff比较两个目录的内容
#!/bin/bash
diff -rq /dir1 /dir236. 定时任务脚本,用于清理/tmp目录
#!/bin/bash
find /tmp -type f -mtime +7 -exec rm -f {} \;
echo "/tmp cleaned up of files older than 7 days."
  1. 创建用户并设置密码(使用chpasswd)
#!/bin/bash
echo "username:password" | sudo chpasswd
sudo useradd -m username
echo "User 'username' created and password set."
  1. 监视磁盘I/O并发送警告(使用iostat和mail)
#!/bin/bash
iowait=$(iostat -dx 12|tail-1| awk '{print $11}')
if["$iowait"-gt 30];then
echo"High IO wait ($iowait%) detected."| mail -s "IO Wait Warning" admin@example.com
fi
  1. 使用rsync进行文件同步
#!/bin/bash
rsync -avz /source/ /destination/
echo "Files synchronized from /source/ to /destination/."
  1. 检查特定端口的开放状态,并记录结果
#!/bin/bash
PORT=80
if nc -z localhost $PORT; then
    echo "Port $PORT is open."
else
    echo "Port $PORT is closed."
fi
  1. 动态创建并管理Docker容器
#!/bin/bash
CONTAINER_NAME="myapp_container"
IMAGE="myapp:latest"

if docker ps -aqf "name=^/$CONTAINER_NAME$";then
echo"Container $CONTAINER_NAME already exists. Restarting..."
    docker restart $CONTAINER_NAME
else
echo"Creating and starting new container $CONTAINER_NAME..."
    docker run -d --name $CONTAINER_NAME$IMAGE
fi42. 批量下载网页并保存为HTML文件#!/bin/bash
URLS=("http://example1.com" "http://example2.com")
for url in "${URLS[@]}"; do
    filename=$(echo "$url" | tr -d '/' | sed 's|^http://||;s|$|.html|')
    curl -o "$filename" "$url"
done
文档更新时间: 2024-09-22 14:30   作者:admin