运维神器!42个必备Shell脚本,一键提升效率

运维工作中,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

2. 监控系统负载

#!/bin/bashuptime | awk -F 'load average:' '{print $2}' | sed 's/,//g'

3. 查找并删除特定大小的文件

#!/bin/bashfind /path/to/search -type f -size +100M -exec rm -f {} \;

4. 列出并杀死特定名称的进程

#!/bin/bashps aux | grep 'process_name' | awk '{print $2}' | xargs kill

5. 监控特定端口的占用情况

#!/bin/bashlsof -i :80

6. 压缩目录

#!/bin/bashtar -czvf archive_name.tar.gz /path/to/directory

7. 解压文件

#!/bin/bashtar -xzvf file_name.tar.gz

8. 批量重命名文件

#!/bin/bashfor file in *.jpg; do  mv "$file" "${file%.jpg}_renamed.jpg"done

9. 检查服务状态

#!/bin/bashsystemctl status nginx

10. 重启服务

#!/bin/bashsystemctl restart nginx

11. 备份MySQL数据库

#!/bin/bashmysqldump -u root -p database_name > backup_file.sql

12. 检查网络连接

#!/bin/bashping -c 4 google.com

13. 更新系统

#!/bin/bashapt-get update && apt-get upgrade -y

或对于基于RPM的系统:

#!/bin/bashyum update -y

14. 清理系统日志

#!/bin/bashfind /var/log/ -type f -mtime +30 -exec rm -f {} \;

15. 监控CPU使用率

#!/bin/bashtop -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}'

16. 列出空目录

#!/bin/bashfind /path/to/search -type d -empty

17. 监控内存使用情况

#!/bin/bashfree -m | grep Mem | awk '{print "Memory Usage: " $3/$2 * 100 "% Used, " $3/2 " GB Used, " $2/2 " GB Total"}'

18. 重启系统

#!/bin/bashreboot

19. 关闭系统

#!/bin/bashshutdown -h now

20. 检查SSH端口是否开放

#!/bin/bashnc -zv localhost 22

21. 监控并自动重启失败的服务

#!/bin/bashSERVICE="myapp"whiletrue;doif! systemctl is-active --quiet $SERVICE;thenecho"Service $SERVICE is down, attempting to restart."        systemctl restart $SERVICEsleep10elseecho"Service $SERVICE is running."sleep60fidone

22. 备份MySQL数据库并压缩

#!/bin/bashDB_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 > $FILENAMEecho "Database backup completed: $FILENAME"

23. 检查并删除旧文件

#!/bin/bashfind /path/to/files -type f -mtime +30 -exec rm {} \;echo "Deleted files older than 30 days."

24. 分析日志文件并发送报警邮件

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

25. 动态生成SSH密钥对

#!/bin/bashKEY_DIR="/home/user/.ssh"KEY_NAME="mykey"mkdir -p $KEY_DIRssh-keygen -t rsa -b 4096 -f $KEY_DIR/$KEY_NAME -N ""echo "SSH key pair generated at $KEY_DIR/$KEY_NAME"

26. 批量更改文件扩展名

#!/bin/bashfor file in *.txt; do    mv "$file" "${file%.txt}.md"doneecho "File extensions changed from .txt to .md"

27. 定时轮询API并处理响应

#!/bin/bashwhiletrue;do    RESPONSE=$(curl -s http://api.example.com/data)
    process_response "$RESPONSE"sleep60doneprocess_response(){# Process the response hereecho"$1"}

28. 检查磁盘空间并自动清理临时文件

#!/bin/bashFREE_SPACE=$(df/| grep /| awk '{print $5}'| sed 's/%//g')if[$FREE_SPACE-le 10];thenecho"Low disk space, cleaning up temporary files..."rm-rf /tmp/*echo"Temporary files cleaned up."fi

29. 自动化部署脚本

#!/bin/bash# 假设使用Git进行版本控制git pull# 构建项目(示例:使用Maven)mvn clean install# 停止当前运行的服务systemctl stop myapp# 部署新构建的应用cp target/myapp.jar /var/lib/myapp/# 重启服务systemctl start myappecho "Deployment completed successfully."

30. 使用awk处理CSV文件

#!/bin/bashawk -F, '{if ($1=="John Doe") print $2}' input.csv

31. 批量更改多个文件的权限

#!/bin/bashfor file in /path/to/files/*; do    chmod 644 "$file"doneecho "Permissions updated for all files in /path/to/files/"

32. 使用curl和jq处理JSON API响应

#!/bin/bashresponse=$(curl -s https://api.example.com/data)echo "$response" | jq '.items[].name'

33. 监控网络带宽使用情况

#!/bin/bashifconfig 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'

34. 递归地搜索并替换文件中的文本

#!/bin/bashfind /path/to/search -type f -exec sed -i 's/old_text/new_text/g' {} +echo "All occurrences of 'old_text' replaced with 'new_text'."

35. 使用diff比较两个目录的内容

#!/bin/bashdiff -rq /dir1 /dir2

36. 定时任务脚本,用于清理/tmp目录

#!/bin/bashfind /tmp -type f -mtime +7 -exec rm -f {} \;echo "/tmp cleaned up of files older than 7 days."

37. 创建用户并设置密码(使用chpasswd)

#!/bin/bashecho "username:password" | sudo chpasswd
sudo useradd -m usernameecho "User 'username' created and password set."

38. 监视磁盘I/O并发送警告(使用iostat和mail)

#!/bin/bashiowait=$(iostat -dx 12|tail-1| awk '{print $11}')if["$iowait"-gt 30];thenecho"High IO wait ($iowait%) detected."| mail -s "IO Wait Warning" admin@example.comfi

39. 使用rsync进行文件同步

#!/bin/bashrsync -avz /source/ /destination/echo "Files synchronized from /source/ to /destination/."

40. 检查特定端口的开放状态,并记录结果

#!/bin/bashPORT=80if nc -z localhost $PORT; then    echo "Port $PORT is open."else    echo "Port $PORT is closed."fi

41. 动态创建并管理Docker容器

#!/bin/bashCONTAINER_NAME="myapp_container"IMAGE="myapp:latest"if docker ps -aqf "name=^/$CONTAINER_NAME$";thenecho"Container $CONTAINER_NAME already exists. Restarting..."    docker restart $CONTAINER_NAMEelseecho"Creating and starting new container $CONTAINER_NAME..."    docker run -d --name $CONTAINER_NAME$IMAGEfi

42. 批量下载网页并保存为HTML文件

#!/bin/bashURLS=("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
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

评论