python 怎么获取一个端口或者一个进程的网络流量

2025-04-09 08:07:57
推荐回答(1个)
回答1:

import socket
import struct
import thread
import threading
import time
import os

net_data = {}
d_net_info = {}
lock = threading.Lock()

def print_data():
while True:
lock.acquire()
for key in net_data:
print "%s %s\n"%(key, net_data[key])
lock.release()
time.sleep(5);

def get_net_info():
net_info = os.popen('netstat -nbo').readlines()

for l in net_info[4:]:
s = l.split()
if len(s)>2:
key = "%s %s"%(s[1],s[2])
key2 = "%s %s"%(s[2],s[1])
else:
if not d_net_info.has_key(key):
d_net_info[key] = s[0]
d_net_info[key2] = s[0]

def get_packet():
HOST = socket.gethostbyname(socket.gethostname())
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))