1
+ # 使用此脚本前先执行 apt install -y net-tools bc 安装依赖
2
+ # */10 * * * * /bin/bash /root/check_trafic.sh >> /root/check.log 2>&1 cron任务,每10分钟运行检查一次
3
+ #! /bin/bash
4
+
5
+ # 定义颜色
6
+ green=" \e[1;32m"
7
+ yellow=" \e[1;33m"
8
+ re=" \033[0m"
9
+
10
+ # 设置流量阈值,单位为 GB
11
+ threshold_traffic=5000
12
+
13
+ # 设置 CPU 使用率阈值,单位为百分比
14
+ threshold_cpu=99
15
+
16
+ # 设置内存使用率阈值,单位为百分比
17
+ threshold_memory=99
18
+
19
+ # 获取 lxdbr0和eth0分支流量
20
+ rx_bytes=$( /sbin/ifconfig enp1s0 | grep " RX packets" | awk ' {print $5}' )
21
+ tx_bytes=$( /sbin/ifconfig enp1s0 | grep " TX packets" | awk ' {print $5}' )
22
+
23
+ # 将字节转换为 GB
24
+ rx_gb=$( echo " scale=2; $rx_bytes / (1024^3)" | bc)
25
+ tx_gb=$( echo " scale=2; $tx_bytes / (1024^3)" | bc)
26
+
27
+ echo -e " ${yellow} RX 流量: $( echo " $rx_gb " | bc) GB${re} "
28
+ echo -e " ${yellow} TX 流量: $( echo " $tx_gb " | bc) GB${re} "
29
+
30
+ # 计算总流量
31
+ total_gb=$( echo " $rx_gb + $tx_gb " | bc)
32
+
33
+ echo -e " ${yellow} 总共使用流量: ${total_gb} GB${re} "
34
+
35
+ # 检查流量是否超过阈值
36
+ if (( $(echo "$total_gb >= $threshold_traffic " | bc - l) )) ; then
37
+ echo -e " ${yellow} 流量已超过阈值,执行关机操作...${re} "
38
+ shutdown -h now
39
+ else
40
+ echo -e " ${green} 流量未超过阈值,继续运行...${re} "
41
+ fi
42
+
43
+ total_memory=$( free -m | awk ' /^Mem:/{print $2}' )
44
+ used_memory=$( free -m | awk ' /^Mem:/{print $3}' )
45
+ memory_usage=$( echo " scale=2; $used_memory / $total_memory * 100" | bc)
46
+
47
+ echo -e " ${yellow} 总内存: ${total_memory} MB${re} "
48
+ echo -e " ${yellow} 已使用内存: ${used_memory} MB${re} "
49
+ echo -e " ${yellow} 当前内存使用率: ${memory_usage} %${re} "
50
+
51
+ # 检查内存使用率是否超过阈值
52
+ if (( $(echo "$memory_usage >= $threshold_memory " | bc - l) )) ; then
53
+ echo -e " ${yellow} 内存使用率已达到${threshold_memory} %, 执行重启操作...${re} "
54
+ shutdown -h now
55
+ else
56
+ echo -e " ${green} 内存使用率未达到${threshold_memory} %, 继续运行...${re} "
57
+ fi
58
+
59
+ # 获取当前 CPU 使用率
60
+ cpu_usage=$( top -bn1 | grep " Cpu(s)" | awk ' {print $2}' | awk -F. ' {print $1}' )
61
+
62
+ echo -e " ${yellow} 当前CPU使用率: ${cpu_usage} %${re} "
63
+
64
+ # 检查 CPU 使用率是否超过阈值
65
+ if (( cpu_usage >= threshold_cpu)) ; then
66
+ echo -e " ${yellow} CPU使用率已达到${threshold_cpu} %, 执行关机操作...${re} "
67
+ shutdown -h now
68
+ else
69
+ echo -e " ${green} CPU使用率未达到${threshold_cpu} %, 继续运行...${re} "
70
+ fi
0 commit comments