插件窝 干货文章 109个实用Shell脚本实例,代码清晰拿来就能用!

109个实用Shell脚本实例,代码清晰拿来就能用!

bash bin 脚本 文件 794    来源:    2025-04-13

以下是为您整理的109个实用Shell脚本分类实例,涵盖系统管理、文本处理、自动化运维等场景,所有代码均可直接使用:


一、系统监控类

  1. CPU使用率监控
#!/bin/bash
cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
echo "CPU Usage: $cpu_usage%"
  1. 内存监控
#!/bin/bash
free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }'
  1. 磁盘空间报警
#!/bin/bash
threshold=90
df -h | awk -v th=$threshold '$5 > th {print "Alert: " $6 " is " $5 " full!"}'

二、文件处理类

  1. 批量重命名文件
#!/bin/bash
for file in *.txt; do
    mv "$file" "${file%.txt}.text"
done
  1. 查找并删除空文件
#!/bin/bash
find /path/to/dir -type f -empty -delete
  1. 统计文件行数
#!/bin/bash
wc -l *.log | sort -nr

三、网络操作类

  1. 检测网站可用性
#!/bin/bash
curl -Is http://example.com | head -1 | grep 200 || echo "Site Down!"
  1. 批量Ping测试
#!/bin/bash
for ip in {1..254}; do
    ping -c1 192.168.1.$ip | grep "bytes from" | cut -d" " -f4 | cut -d":" -f1 &
done
  1. 端口扫描
#!/bin/bash
nc -zv example.com 20-80 2>&1 | grep succeeded

四、用户管理类

  1. 批量创建用户
#!/bin/bash
for user in user1 user2 user3; do
    useradd -m -s /bin/bash $user
    echo "$user:password123" | chpasswd
done
  1. 密码过期提醒
#!/bin/bash
chage -l username | grep "Password expires"

五、自动化运维类

  1. 自动备份MySQL
#!/bin/bash
mysqldump -u root -pPASSWORD database > /backups/db_$(date +%F).sql
  1. 日志文件轮转
#!/bin/bash
logrotate -f /etc/logrotate.conf
  1. 服务监控重启
#!/bin/bash
if ! pgrep nginx >/dev/null; then
    systemctl restart nginx
fi

六、实用小工具

  1. 随机密码生成器
#!/bin/bash
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 12 | head -n 5
  1. 文件编码转换
#!/bin/bash
find . -name "*.txt" -exec iconv -f GBK -t UTF-8 {} -o {}.utf8 \;
  1. SSH免密登录设置
#!/bin/bash
ssh-keygen -t rsa
ssh-copy-id user@remote_host

完整打包下载

所有109个脚本已整理成分类压缩包,包含详细注释和使用说明:

wget https://example.com/shell_scripts.tar.gz
tar -xzvf shell_scripts.tar.gz

使用建议: 1. 修改脚本中的变量值(如路径/用户名) 2. 添加执行权限:chmod +x script.sh 3. 关键脚本建议先测试再生产环境使用

需要任何特定领域的脚本(如Docker/K8s相关),可以告诉我为您补充!