netbeacon/nb_collect.py

48 lines
1.4 KiB
Python
Raw Normal View History

import dpkt
import pcap
import re
import sys
2013-06-11 06:20:54 +00:00
import socket
from optparse import OptionParser
2012-12-08 12:40:10 +00:00
usage = "usage: %prog [options]"
parser = OptionParser(usage)
parser.add_option("-i","--interface", dest="interface", help="live capture on interface (default:lo)")
parser.add_option("-r","--read", dest="filedump", help="read pcap file")
2013-06-11 06:20:54 +00:00
parser.add_option("-e","--extended", dest="extended", action="store_true", help="enable extended format including pcap timestamp")
(options, args) = parser.parse_args()
if options.interface:
interface = options.interface
else:
interface = "lo"
if options.filedump:
interface = options.filedump
pc = pcap.pcap(interface)
pc.setfilter("port 12345 and udp")
decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback,
pcap.DLT_NULL:dpkt.loopback.Loopback,
pcap.DLT_EN10MB:dpkt.ethernet.Ethernet }[pc.datalink()]
try:
sys.stderr.write('listening on %s: %s' % (pc.name, pc.filter))
for ts, pkt in pc:
2013-06-11 06:20:54 +00:00
eth = dpkt.ethernet.Ethernet(pkt)
ip = eth.data
udp = ip.data
if re.search("^nb", udp.data):
if options.extended:
2013-06-11 06:20:54 +00:00
print str(ts)+"|"+str(socket.inet_ntoa(ip.src))+"|"+udp.data
else:
print udp.data
except KeyboardInterrupt:
nrecv, ndrop, nifdrop = pc.stats()
sys.stderr.write('\n%d packets received by filter' % nrecv)
sys.stderr.write('%d packets dropped by kernel' % ndrop)