1

I've created a few light monitoring scripts for a server I've set up.

One of the scripts tests for sustained high CPU load, and has been sending notices once a day in the middle of the night. But the alerts have been sent at different times each nigh, so the CPU load doesn't seem to be related to any of the regular cron jobs I have set up.

I know I can use top to view CPU usage breakdown in realtime, but is there any tool I can use in a bash script that would report what apps are using the most CPU % at a given moment in time?

3
  • Did you try ps -rf? Commented Feb 21, 2022 at 16:02
  • @RenaudPacalet Thanks for the suggestion. That only seems to list processes for the active TTY though, and doesn't list processes being run by other users or background processes. Eg, if I look in top there are usually dozens of processes running, but ps -rf only shows one process (itself). It won't tell me if a background process is chewing up the CPU, or if someone has somehow managed to compromise the server to run processes from another system account. Commented Feb 21, 2022 at 17:00
  • man ps is your friend. Commented Feb 21, 2022 at 17:04

1 Answer 1

3

Try

ps -eo pid,cmd,%cpu --sort=-%cpu | head

This reports:

  • pid: process id
  • cmd: command
  • %cpu: percentage of cpu used
  • --sort=-%cpu: sort by decreasing cpu usage
  • | head: show only the top 10 lines of the output, adjust as required.

You can set this command in crontab, have it run every minute and output it a log file. It will give you an idea of what is going on at night.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is exactly what I was looking for. I've also added 'user' to the list of columns to report, so this should now also report which system account the given processes are running under. Thanks again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.