Created
February 9, 2013 02:31
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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