Score:0

How to monitor cpu and memory usage?

la flag

How to write script monitoring cpu and memory usage then prints a warning when usage is 70% (red warning)?

EDIT:

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"

It keeps giving me 0% usage of CPU and message isn't printed

in flag
Welcome to AskUbuntu! Have you seen the answers [to this question](https://askubuntu.com/q/56266/1222991)? If so could you [edit] your question to state what you've already tried and what challenges you're facing? As it stands, this looks like a homework question
linuxnoobie avatar
la flag
I tried few things, i will edit my question
Score:1
ng flag

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)

Bash:

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

For example, on my nettop, the second solution produced this:

zenbooster@zenpc:~$ ./usage.sh
CPU Usage: 1.2%
Memory Usage: 63%
linuxnoobie avatar
la flag
Thanks for your help, but is there anyways to convert it to linux format since im not familiar with python.
zenbooster avatar
ng flag
Added solution on Bash.
linuxnoobie avatar
la flag
Thank you so much !
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.