Skip to content

Instantly share code, notes, and snippets.

@fqrouter
Created February 9, 2013 02:31
Show Gist options
  • Save fqrouter/4743565 to your computer and use it in GitHub Desktop.
Save fqrouter/4743565 to your computer and use it in GitHub Desktop.
make tcpdump output to stdout and use dpkt to parse the pcap file captured
@contextlib.contextmanager
def capture(ifname, src, dst):
events = []
filter = '(host %s and host %s) or icmp[0] = 11' % (src, dst)
p = subprocess.Popen(
['tcpdump', '-i', ifname, '-w', '-', filter],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
try:
yield events
finally:
p.terminate()
captured_bytes = p.stdout.read()
fake_file = StringIO(captured_bytes)
fake_file.__dict__['name'] = ''
fake_file.__dict__['fileno'] = lambda: None
for timestamp, eth_frame_bytes in dpkt.pcap.Reader(fake_file):
eth_frame = dpkt.ethernet.Ethernet(eth_frame_bytes)
if not hasattr(eth_frame, 'ip'):
continue
events.append((timestamp, eth_frame.ip))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment