一个监控系统进程网络流量的程序
程序要求使用python2.7版本
1 import socket 2 import struct 3 import thread 4 import threading 5 import time 6 import os 7 8 net_data = {} 9 d_net_info = {} 10 lock = threading.Lock() 11 12 def print_data(): 13 while True: 14 lock.acquire() 15 for key in net_data: 16 print "%s %s\n"%(key, net_data[key]) 17 lock.release() 18 time.sleep(5); 19 20 def get_net_info(): 21 net_info = os.popen('netstat -nbo').readlines() 22 23 for l in net_info[4:]: 24 s = l.split() 25 if len(s)>2: 26 key = "%s %s"%(s[1],s[2]) 27 key2 = "%s %s"%(s[2],s[1]) 28 else: 29 if not d_net_info.has_key(key): 30 d_net_info[key] = s[0] 31 d_net_info[key2] = s[0] 32 33 def get_packet(): 34 HOST = socket.gethostbyname(socket.gethostname()) 35 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) 36 s.bind((HOST, 0)) 37 s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 38 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) 39 net_data["unknow"] = 0 40 41 while True: 42 buf = s.recvfrom(65565) 43 port = struct.unpack('HH', buf[0][20:24]) 44 45 src_ip = "%d.%d.%d.%d"%struct.unpack('BBBB', buf[0][12:16]) 46 dest_ip ="%d.%d.%d.%d"%struct.unpack('BBBB', buf[0][16:20]) 47 src_port = socket.htons(port[0]) 48 dest_port = socket.htons(port[1]) 49 50 data_len = len(buf[0]) 51 key="%s:%d %s:%d"%(src_ip,src_port,dest_ip,dest_port) 52 if not d_net_info.has_key(key): 53 get_net_info() 54 55 if d_net_info.has_key(key): 56 key2 ="%s %s"%(key,d_net_info[key]) 57 if net_data.has_key(key2): 58 net_data[key2] =net_data[key2]+data_len 59 else: 60 net_data[key2] = data_len 61 else: 62 net_data["unknow"] =net_data["unknow"] + data_len 63 64 thread.start_new_thread(print_data,()) 65 get_packet() 66 os.exit()