Linux systems use python to monitor the network interface to get input and output from the network

  • 2020-04-02 13:19:27
  • OfStack

Net.py gets the input and output of the network interface


#!/usr/bin/env Python
import time
import sys
if len(sys.argv) > 1:
 INTERFACE = sys.argv[1]
else:
 INTERFACE = 'eth0'
STATS = []
print 'Interface:',INTERFACE
def rx():
 ifstat = open('/proc/net/dev').readlines()
 for interface in  ifstat:
  if INTERFACE in interface:
   stat = float(interface.split()[1])
   STATS[0:] = [stat]
def tx():
 ifstat = open('/proc/net/dev').readlines()
 for interface in  ifstat:
  if INTERFACE in interface:
   stat = float(interface.split()[9])
   STATS[1:] = [stat]
print 'In   Out'
rx()
tx()
while True:
 time.sleep(1)
 rxstat_o = list(STATS)
 rx()
 tx()
 RX = float(STATS[0])
 RX_O = rxstat_o[0]
 TX = float(STATS[1])
 TX_O = rxstat_o[1]
 RX_RATE = round((RX - RX_O)/1024/1024,3)
 TX_RATE = round((TX - TX_O)/1024/1024,3)
 print RX_RATE ,'MB  ',TX_RATE ,'MB'

A quick note on listing 4: listing 4 reads the information in /proc/net/dev. File operations in Python can be done through the open function, which is very much like fopen in C. Get a file object through the open function, and then call methods like read(), write() to read and write to the file. Also, Python makes it easy to read the contents of a text file into a string variable that you can manipulate. The file object provides three "read" methods: read(), readline(), and readlines(). Each method can accept a variable to limit the amount of data read at a time, but they typically do not use variables. .read() reads the entire file at a time, which is typically used to put the contents of the file into a string variable. However,.read() generates the most direct string representation of the contents of the file, but it is not necessary for continuous line-oriented processing, and it is not possible if the file is larger than available memory. The difference between.readline() and.readlines() is that the latter reads the entire file at once, like.read(). .readlines() automatically parses the contents of the file into a list of lines that can be accessed by Python's for... The in... The structure is processed. On the other hand,.readline() reads only one line at a time, and is usually much slower than.readlines(). .readline() should only be used if there is not enough memory to read the entire file at once. Finally, listing 4 prints out the input and output of the network interface.
You can use the Python command to run the script net.py, as shown in figure 4

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201401/20140115112052.jpg? 2014015112116 ">


Related articles: