SHARE
TWEET

SF Python Project Night 4/19/2017: Working with Binary Data

a guest Apr 20th, 2017 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/env python3
  2.  
  3. import sys
  4. fh = open('/Users/Derek/Downloads/net.cap', 'rb')
  5. fh.seek(24)  # Skip the header
  6.  
  7. loop_count = 0
  8. final_data = dict()
  9. while True:
  10.     timestamp_sec_bytes = fh.read(4)
  11.     if not timestamp_sec_bytes:
  12.         break
  13.     loop_count += 1
  14.     timestamp_ms_bytes = fh.read(4)
  15.     packet_size_bytes = fh.read(4)
  16.     packet_len_bytes = fh.read(4)
  17.  
  18.     packet_size = int.from_bytes(packet_size_bytes, byteorder="little")
  19.     ethernet_frame_bytes = fh.read(packet_size)
  20.  
  21.     ip_datagram_bytes = ethernet_frame_bytes[14:]
  22.     ip_datagram_header_length = 4*(ip_datagram_bytes[0] & 0x0F)
  23.     #print("Header length: {}".format(ip_datagram_header_length))
  24.  
  25.     source_ip_address = ip_datagram_bytes[12:16]
  26.     formatted_ip_source = ["{:d}".format(b)for b in source_ip_address]
  27.     #print("Source IP: {}".format(".".join(formatted_ip_source)))
  28.  
  29.     dest_ip_address = ip_datagram_bytes[16:20]
  30.     formatted_ip_dest = ["{:d}".format(b)for b in dest_ip_address]
  31.     #print("Dest IP:   {}".format(".".join(formatted_ip_dest)))
  32.     if ".".join(formatted_ip_dest) == "192.30.252.154":
  33.         continue
  34.  
  35.     tcp_payload = ip_datagram_bytes[ip_datagram_header_length:]
  36.     seq_num = int.from_bytes(tcp_payload[4:8], byteorder="little")
  37.     print("Sequence: {}".format(seq_num))
  38.  
  39.     tcp_data_offset = tcp_payload[12] >> 4
  40.     print("TCP Data Offset: {}".format(tcp_data_offset))
  41.     final_data[seq_num] = tcp_payload[tcp_data_offset*4:]
  42.  
  43.     #print(ethernet_frame_bytes[0:22])
  44.  
  45.     # print(packet_size)
  46.     print("")
  47.     # break
  48.  
  49. print("Found " + str(loop_count) + " packets")
  50. print("There are {} items in our dictionary".format(len(final_data)))
RAW Paste Data
Want to get better at Python?
Learn to code Python in 2017
Top