如何监控CPU和内存的使用情况?

如何监控CPU和内存的使用情况?

如何编写脚本来监控 CPU 和内存使用情况,然后在使用率达到 70% 时打印警告(红色警告)?

编辑:

cpuUsage=$(top -bn1 | awk '/Cpu/ { print $2}')
memUsage=$(free -m | awk '/Mem/{print $3}')
echo "CPU Usage: $cpuUsage%"
echo "Memory Usage: $memUsage%"
if [ "$cpuUsage" -ge 70]; then
echo -e "The system is not utilizing"

CPU 使用率一直为 0%,并且没有打印任何消息

答案1

Python:

#!/usr/bin/env python3
import psutil
import time

threshold = 70 # percent

def beep():
  print('***[ BEEP ]***')

while(1):
  cpu_pc = psutil.cpu_percent()
  mem_pc = psutil.virtual_memory().percent
  print(f'cpu: {cpu_pc}%; mem: {mem_pc}%')
  if cpu_pc >= threshold or mem_pc >= threshold:
    beep()

  time.sleep(0.5)

重击:

cpuUsage=$(top -bn1 | awk '/Cpu/ { print $2}')
memTotal=$(free -m | awk '/Mem/{print $2}')
memUsage=$(free -m | awk '/Mem/{print $3}')
memUsage=$(( (memUsage * 100) / memTotal ))
echo "CPU Usage: $cpuUsage%"
echo "Memory Usage: $memUsage%"
if (( $(echo "$cpuUsage >= 70" |bc -l) )); then
  echo -e "The system is not utilizing"
fi

例如,在我的网上,第二个解决方案产生了这样的结果:

zenbooster@zenpc:~$ ./usage.sh
CPU Usage: 1.2%
Memory Usage: 63%

相关内容