This article introduces how to use Python to view network traffic information of the system. if you need it, you can refer to it for reference. Let's take a look.
Preface
The traffic information can be directly stored in/proc/net/dev
To view, the program implemented by the author uses the command:
python net.py interface
Whereinterface
It is the name of the network card, which network card is used, and which network card is available on the computer.
sudo ifconfig
.
The Python implementation program is as follows:
# coding:utf-8import sys, time, os'''Inter-| Receive | Transmit face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed lo: 28169 364 0 0 0 0 0 0 28169 364 0 0 0 0 0 0 wlan1: 7432984 6018 0 0 0 0 0 0 681381 6115 0 0 0 0 0 0vmnet1: 0 0 0 0 0 0 0 0 0 56 0 0 0 0 0 0vmnet8: 0 0 0 0 0 0 0 0 0 55 0 0 0 0 0 0 eth0: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0'''_unit_=['B','KB','MB','GB','TB']def get_net_data(interface): for line in open('/proc/net/dev', 'r'): if line.split(':')[0].find(interface)>=0: return map(int, line.split(':')[1].split())def convert_bytes_to_string(b): cnt = 0 while b >= 1024.0: b = float(b) / 1024.0 cnt += 1 return '%.2f%s'%(b,_unit_[cnt])if __name__ == '__main__': interface = sys.argv[1] while True: net_data = get_net_data(interface) receive_data_bytes = net_data[0] transmit_data_bytes = net_data[8] os.system('clear') print 'Interface:%s -> Receive Data: %s Transmit Data: %s'%(interface, convert_bytes_to_string(receive_data_bytes), convert_bytes_to_string(transmit_data_bytes)) time.sleep(1)
Program entry fromif name=='main'
First, get it through parameters.interface
And then callget_net_data()
The function obtains the traffic information, followed by some data processing processes.
Summary
The above is all about this article. I hope to help you in your study or work. if you have any questions, please leave a message.
For more information about how to view the network traffic of the system in python, refer to the PHP Chinese network!