0

I'm well aware that variants of this question have been asked before, but I still haven't found a particularly good answer.

What I'm trying to do is write a Python script that will measure the current bandwidth use and the total bytes uploaded/downloaded by process and all of its children and kill it if either of these values exceeds a user-defined threshold. Its purpose will be to limit the network usage of a backup client.

I've considered a couple of options for measuring process bandwidth:

  • bwmon does exactly what I want, but frustratingly it won't work for me in its current form. The problem is that it relies on reading bytes= and packets= fields from /proc/net/ip_conntrack in order to measure bandwidth. For some reason these fields just don't exist for me - I suspect it might be to do different kernel versions.

  • Currently the most workable solution I've found would be to parse the output of strace -e trace=recvfrom,sendto -p <PID> as per this suggestion. However, this is a bit messy and raises nasty permissions issues - in order to attach to an existing process I would need to sudo strace, and I'd prefer to avoid running shell commands with superuser privileges from within scripts.

I wonder if anyone has a more elegant suggestion?

I am not very familiar with the contents of /proc, but if there is some other log file that will list packet sizes and counts then I could perhaps modify bwmon to use this instead.

Community
  • 1
  • 1
ali_m
  • 71,714
  • 23
  • 223
  • 298

1 Answers1

3

Not a programming-related answer, but: try doing this:

sudo modprobe ip_conntrack
sysctl -w net.netfilter.nf_conntrack_acct=1

Enabling the module and sysctl setting globally is distribution-specific, but at least until you reboot, bwmon should work if it needs bytes and packets in /proc/net/ip_conntrack.

Based on http://ubuntuforums.org/showthread.php?t=2046187 and http://forums.gentoo.org/viewtopic-p-6677939.html (and thereby ultimately on Google).

Walter Mundt
  • 24,753
  • 5
  • 53
  • 61
  • Nice, that seemed to do the trick: `bytes=` and `packets=` are now reported in `/proc/net/ip_conntrack` and `bwmon` now seems to work ok! For anyone else who might be interested, I added `ip_conntrack` to `/etc/modules` so that it loads at boot time, and I added `net.netfilter.nf_conntrack_acct=1` to `/etc/sysctl.conf` to make logging of packet size and count persistent. – ali_m Aug 24 '12 at 10:29