使用pylibcap
。它提供了一個libpcap的接口,這是Linux上數據包嗅探的事實標準。要解析數據包,您可能需要使用construct
庫,因爲它已包含用於TCP數據包的解析器。
這裏有一個小例子程序:
import pcap
from construct.protocols.ipstack import ip_stack
def print_packet(pktlen, data, timestamp):
if not data:
return
stack = ip_stack.parse(data)
payload = stack.next.next.next
print payload
p = pcap.pcapObject()
p.open_live('eth0', 1600, 0, 100)
p.setfilter('dst port 80', 0, 0)
print 'Press CTRL+C to end capture'
try:
while True:
p.dispatch(1, print_packet)
except KeyboardInterrupt:
print # Empty line where ^C from CTRL+C is displayed
print '%d packets received, %d packets dropped, %d packets dropped by interface' % p.stats()