nethogs is a great utility to monitor network traffic by process. However, it is "interactive" and not suitable to be used in script... How can I achieve the following using nethogs or similar tool:
I want to monitor a process (by its id or name) for a few second, get its traffic (as a number, in any unit such as KB/s), if the traffic is lower than a threshold, the script returns non-zero.
Thanks a lot.
EDIT:
- Debian 10 Server
- The program I need to monitor is ffmpeg, which push RTSP stream to remote RTMP server. i.e. it is a "client", not "server".
- If possible I'd like to avoid iptables. Also, since there are many instance of ffmpeg running, find out traffice for each and every instance is vital. I don't know if iptables can trace process or not??
If your processes are listening, like servers (HTTP/HTTPS/SSH), you need know what ports processes are binding to then you can iptables accounting rules.
You didn't say what operating system your using, but this script should be fairly adaptable.
This will monitor ports 80,443,22 incoming and outgoing.
you can put the following in your script to show the counters.
iptables -L INET_IN_PORT -v -n
iptables -L INET_OUT_PORT -v -n
$ iptables -L INET_IN_PORT -v -x
You may want to reset the counters when you've queried them. Thus if you query them every two seconds you can check if the exceed a value you define.
iptables -L INET_IN_PORT -Z
iptables -L INET_OUT_PORT -Z
This should give you enough for basis for a script to exactly what you need.
if your processes use dynamics ports on each load, then query what ports they are using and configure iptables accordingly.
I hope this helps, good luck!
I found that nethogs has some command line options, especially -t (trace mode), which is suitable for use in scripts:
This will count all traffic on the eno1 interface for 5 seconds, then quit.