This article describes how to use the python monitoring network interface in linux to obtain network input and output information. For more information, see net. py.
The code is as follows:
#! /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 brief description of listing 4: Listing 4 reads the information in/proc/net/dev. file operations in Python can use the open function, which is indeed similar to fopen in C. Obtain a file object through the open function, and then call the read (), write () and other methods to read and write the object. In addition, it is very easy for Python to read the content of a text file into string variables that can be operated. The file object provides three "read" methods: read (), readline (), and readlines (). Each method can accept a variable to limit the amount of data read each time, but they usually do not use variables. . Read () reads the entire file every time. it is usually used to put the file content into a string variable. However. read () generates the most direct string representation of the file content, but it is unnecessary for continuous row-oriented processing, and if the file is larger than the available memory, this processing is not possible .. The difference between readline () and. readlines () is that the latter reads the entire file at a time, like. read .. Readlines () automatically analyzes the file content into a list of rows, which can be processed by the structure of Python for... in. On the other hand,. readline () reads only one row at a time, which is usually much slower than. readlines. Use. readline () only when there is not enough memory to read the entire file at a time (). Listing 4 shows the input and output of the network interface.
You can use the Python command to run the script. net. py. The result is shown in figure 4.