运维神器!41个必备Shell脚本,一键提升效率!
时间:2024-9-21 20:38 作者:Anglei 分类: Linux
运维工作中,Shell 脚本是非常强大的工具,可以帮助自动化执行各种任务。以下是41个实用的Shell脚本示例,这些脚本可以直接或稍作修改后用于实际运维工作中,供参考
-
检查磁盘空间
#!/bin/bash df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $6 }' | while read output; do echo $output if [ $(echo $output | awk '{print $1}' | sed 's/%//g') -ge 80 ]; then echo "Warning: $output" fi done
-
监控系统负载
#!/bin/bash uptime | awk -F 'load average:' '{print $2}' | sed 's/,//g'
-
查找并删除特定大小的文件
#!/bin/bash find /path/to/search -type f -size +100M -exec rm -f {} \;
-
列出并杀死特定名称的进程
#!/bin/bash ps aux | grep 'process_name' | awk '{print $2}' | xargs kill
-
监控特定端口的占用情况
#!/bin/bash lsof -i :80
-
压缩目录
#!/bin/bash tar -czvf archive_name.tar.gz /path/to/directory
-
解压文件
#!/bin/bash tar -xzvf file_name.tar.gz
-
批量重命名文件
#!/bin/bash for file in *.jpg; do mv "$file" "${file%.jpg}_renamed.jpg" done
-
检查服务状态
#!/bin/bash systemctl status nginx
-
重启服务
#!/bin/bash systemctl restart nginx
-
备份MySQL数据库
#!/bin/bash mysqldump -u root -p database_name > backup_file.sql
-
检查网络连接
#!/bin/bash ping -c 4 google.com
-
更新系统
#!/bin/bash apt-get update && apt-get upgrade -y || yum update -y
-
清理系统日志
#!/bin/bash find /var/log/ -type f -mtime +30 -exec rm -f {} \;
-
监控CPU使用率
#!/bin/bash top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\\1/" | awk '{print 100 - $1"%"}'
-
列出空目录
#!/bin/bash find /path/to/search -type d -empty
-
监控内存使用情况
#!/bin/bash free -m | grep Mem | awk '{print "Memory Usage: " $3/$2 * 100 "% Used, " $3/2 " GB Used, " $2/2 " GB Total"}'
-
重启系统
#!/bin/bash reboot
-
关闭系统
#!/bin/bash shutdown -h now
-
检查SSH端口是否开放
#!/bin/bash nc -zv localhost 22
-
监控并自动重启失败的服务
#!/bin/bash SERVICE="myapp" while true; do if ! systemctl is-active --quiet $SERVICE; then echo "Service $SERVICE is down, attempting to restart." systemctl restart $SERVICE sleep 10 else echo "Service $SERVICE is running." sleep 60 fi done
-
备份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"
-
检查并删除旧文件
#!/bin/bash find /path/to/files -type f -mtime +30 -exec rm {} \; echo "Deleted files older than 30 days."
-
分析日志文件并发送报警邮件
#!/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
-
动态生成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"
-
批量更改文件扩展名
#!/bin/bash for file in *.txt; do mv "$file" "${file%.txt}.md" done echo "File extensions changed from .txt to .md"
-
定时轮询API并处理响应
#!/bin/bash while true; do RESPONSE=$(curl -s http://api.example.com/data) process_response "$RESPONSE" sleep 60 done process_response(){ # Process the response here echo "$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
-
自动化部署脚本
#!/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."
-
使用awk处理CSV文件
#!/bin/bash awk -F, '{if ($1=="John Doe") print $2}' input.csv
-
批量更改多个文件的权限
#!/bin/bash for file in /path/to/files/*; do chmod 644 "$file" done echo "Permissions updated for all files in /path/to/files/"
-
使用curl和jq处理JSON API响应
#!/bin/bash response=$(curl -s https://api.example.com/data) echo "$response" | jq '.items[].name'
-
监控网络带宽使用情况
#!/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'
-
递归地搜索并替换文件中的文本
#!/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'."
-
使用diff比较两个目录的内容
#!/bin/bash diff -rq /dir1 /dir2
-
定时任务脚本,用于清理/tmp目录
#!/bin/bash find /tmp -type f -mtime +7 -exec rm -f {} \; echo "/tmp cleaned up of files older than 7 days."
-
创建用户并设置密码(使用chpasswd)
#!/bin/bash echo "username:password" | sudo chpasswd sudo useradd -m username echo "User 'username' created and password set."
-
监视磁盘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
-
使用rsync进行文件同步
#!/bin/bash rsync -avz /source/ /destination/ echo "Files synchronized from /source/ to /destination/."
-
检查特定端口的开放状态,并记录结果
#!/bin/bash PORT=80 if nc -z localhost $PORT; then echo "Port $PORT is open." else echo "Port $PORT is closed." fi
-
批量下载网页并保存为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

推荐阅读:
![]() 路过(0) |
![]() 雷人(0) |
![]() 握手(0) |
![]() 鲜花(0) |
![]() 鸡蛋(0) |