How to find network usage programmatically in Linux
I’m trying to count the total network traffic on the wlan1
interface from python code. So far, I’ve tried ethtool
, iftop
, ifstat
, nethogs
, but most of these tools show the ncurses interface (text library interface).
I’ve tried something like this
import subprocess
nw_usage = subprocess. Popen(['ifstat', '-i', 'wlan1'])
But it doesn’t give me the network usage value.
I don’t know how to get the network usage value in a single variable from the ncurses interface. (And I feel like there would be better ways to calculate network usage).
Any help or guidance would be a great help.
Thanks
Solution
I know it’s been a few weeks since this question, but maybe this answer is still useful 🙂
You can read device statistics from /proc/net/dev. Read the bytes sent/received and calculate the difference in a time interval. Here are some simple Python scripts that I cracked together
import re
import time
# A regular expression which separates the interesting fields and saves them in named groups
regexp = r"""
\s* # a interface line starts with none, one or more whitespaces
(? P<interface>\w+):\s+ # the name of the interface followed by a colon and spaces
(? P<rx_bytes>\d+)\s+ # the number of received bytes and one or more whitespaces
(? P<rx_packets>\d+)\s+ # the number of received packets and one or more whitespaces
(? P<rx_errors>\d+)\s+ # the number of receive errors and one or more whitespaces
(? P<rx_drop>\d+)\s+ # the number of dropped rx packets and ...
(? P<rx_fifo>\d+)\s+ # rx fifo
(? P<rx_frame>\d+)\s+ # rx frame
(? P<rx_compr>\d+)\s+ # rx compressed
(? P<rx_multicast>\d+)\s+ # rx multicast
(? P<tx_bytes>\d+)\s+ # the number of transmitted bytes and one or more whitespaces
(? P<tx_packets>\d+)\s+ # the number of transmitted packets and one or more whitespaces
(? P<tx_errors>\d+)\s+ # the number of transmit errors and one or more whitespaces
(? P<tx_drop>\d+)\s+ # the number of dropped tx packets and ...
(? P<tx_fifo>\d+)\s+ # tx fifo
(? P<tx_frame>\d+)\s+ # tx frame
(? P<tx_compr>\d+)\s+ # tx compressed
(? P<tx_multicast>\d+)\s* # tx multicast
"""
pattern = re.compile(regexp, re. VERBOSE)
def get_bytes(interface_name):
'''returns tuple of (rx_bytes, tx_bytes) '''
with open('/proc/net/dev', 'r') as f:
a = f.readline()
while(a):
m = pattern.search(a)
# the regexp matched
# look for the needed interface and return the rx_bytes and tx_bytes
if m:
if m.group('interface') == interface_name:
return (m.group('rx_bytes'),m.group('tx_bytes'))
a = f.readline()
while True:
last_time = time.time()
last_bytes = get_bytes('wlan0')
time.sleep(1)
now_bytes = get_bytes('wlan0')
print "rx: %s B/s, tx %s B/s" % (int(now_bytes[0]) - int(last_bytes[0]), int(now_bytes[1]) - int(last_bytes[1]))