分享

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

 新用户62592529 2024-09-23 发布于四川

运维工作中,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/bash
uptime | awk -F 'load average:' '{print $2}' | sed 's/,//g'

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

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

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

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

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

#!/bin/bash
lsof -i :80

6. 压缩目录

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

7. 解压文件

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

8. 批量重命名文件

#!/bin/bash
for file in *.jpg; do
  mv '$file' '${file%.jpg}_renamed.jpg'
done

9. 检查服务状态

#!/bin/bash
systemctl status nginx

10. 重启服务

#!/bin/bash
systemctl restart nginx

11. 备份MySQL数据库

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

12. 检查网络连接

#!/bin/bash
ping -c 4 google.com

13. 更新系统

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

或对于基于RPM的系统:

#!/bin/bash
yum update -y

14. 清理系统日志

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

15. 监控CPU使用率

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

16. 列出空目录

#!/bin/bash
find /path/to/search -type d -empty

17. 监控内存使用情况

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

18. 重启系统

#!/bin/bash
reboot

19. 关闭系统

#!/bin/bash
shutdown -h now

20. 检查SSH端口是否开放

#!/bin/bash
nc -zv localhost 22

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

#!/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

22. 备份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'

23. 检查并删除旧文件

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

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

#!/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@
fi

25. 动态生成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'

26. 批量更改文件扩展名

#!/bin/bash
for file in *.txt; do
    mv '$file' '${file%.txt}.md'
done
echo 'File extensions changed from .txt to .md'

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

#!/bin/bash
whiletrue;do
    RESPONSE=$(curl -s http://api./data)
    process_response '$RESPONSE'
sleep60
done

process_response(){
# Process the response here
echo'$1'
}

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

#!/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

29. 自动化部署脚本

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

30. 使用awk处理CSV文件

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

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

#!/bin/bash
for file in /path/to/files/*; do
    chmod 644 '$file'
done
echo 'Permissions updated for all files in /path/to/files/'

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

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

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

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

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

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

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

#!/bin/bash
diff -rq /dir1 /dir2

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

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

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

#!/bin/bash
echo 'username:password' | sudo chpasswd
sudo useradd -m username
echo 'User 'username' created and password set.'

38. 监视磁盘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@
fi

39. 使用rsync进行文件同步

#!/bin/bash
rsync -avz /source/ /destination/
echo 'Files synchronized from /source/ to /destination/.'

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

#!/bin/bash
PORT=80
if nc -z localhost $PORTthen
    echo 'Port $PORT is open.'
else
    echo 'Port $PORT is closed.'
fi

41. 动态创建并管理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
fi

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

#!/bin/bash
URLS=('http://' 'http://')
for url in '${URLS[@]}'do
    filename=$(echo '$url' | tr -d '/' | sed 's|^http://||;s|$|.html|')
    curl -o '$filename' '$url'
done

推荐关注

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约