I need some command line snippets to get the current CPU Usage (in percent) and the current network bandwith usage.
To get the CPU-Usage i found top -bn1 | grep "Cpu(s)"
But it always give me
%Cpu(s): 12,3 us, 3,6 sy, 0,0 ni, 83,7 id, 0,3 wa, 0,0 hi, 0,0 si, 0,0 st
The numbers given by this command are never changing. I tried to set the server under heavy-load and i got 83,7% idle as well.
As well i found ps aux|awk 'NR > 0 { s +=$3 }; END {print "cpu %",s}'
These values are changing, what looks nice, but i get values like
403.8
407.3
524.6
553.2
And I don't know, what these values mean I have 4 cores in my computer so i would expect 400% CPU-Usage means all cores are on 100% But how can I have more than 400% usage? even, if htop says the average CPU usage is about 3 - 5%
For the network traffic monitor I haven't found anything usable. I just need the numbers in/out in kbps to use them in another program / script
Thanks a lot four your help :)
For the network usage you could poll data directly from /proc/net/dev.
Try the command uptime which gives you the uptime and load averages for the past 1, 5, and 15 minutes.
The bandwidth can be found in the files /sys/class/net/$1/statistics/rx_bytes and /sys/class/net/$1/statistics/tx_bytes
You should remember the current value and look again after a second to get the current bandwidth usage.
One word regarding load: A lot of people think that CPU usage is a useful measurement. That's not correct. It's easy to have a system where many processes are waiting for data (network, disk, etc) but since they are waiting, the CPU load will be low. If you try to work on such a system, it will still feel sluggish.
So the system load is a much better meter for how "busy" your system is.
And you should have a look at tools like atop which monitor the system constantly and give you historical data, like the processes which hogged the CPU in the past. (intro)
EDIT The reason why top -bn1 | grep always prints the same result is because you're measuring the startup of top itself. You need to run a monitor over an extended period of time before you can start use the values it gives you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With