TestUtil.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/python3
  2. import scapy.all
  3. import scapy.packet
  4. # You could compare pcaps by byte or by hash too, but this class tells you
  5. # where exactly pcaps differ
  6. class PcapComparator:
  7. def compare_files(self, file: str, other_file: str):
  8. self.compare_captures(scapy.all.rdpcap(file), scapy.all.rdpcap(other_file))
  9. def compare_captures(self, packetsA, packetsB):
  10. if len(packetsA) != len(packetsB):
  11. self.fail("Both pcap's have to have the same amount of packets")
  12. for i in range(len(packetsA)):
  13. p, p2 = packetsA[i], packetsB[i]
  14. if abs(p.time - p2.time) > (10 ** -7):
  15. self.fail("Packets no %i in the pcap's don't appear at the same time" % (i + 1))
  16. self.compare_packets(p, p2, i + 1)
  17. def compare_packets(self, p: scapy.packet.BasePacket, p2: scapy.packet.BasePacket, packet_number: int):
  18. if p == p2:
  19. return
  20. while type(p) != scapy.packet.NoPayload or type(p2) != scapy.packet.NoPayload:
  21. if type(p) != type(p2):
  22. self.fail("Packets %i are of incompatible types: %s and %s" % (packet_number, type(p).__name__, type(p2).__name__))
  23. for field in p.fields:
  24. if p.fields[field] != p2.fields[field]:
  25. packet_type = type(p).__name__
  26. v, v2 = p.fields[field], p2.fields[field]
  27. self.fail("Packets %i differ in field %s.%s: %s != %s" %
  28. (packet_number, packet_type, field, v, v2))
  29. p = p.payload
  30. p2 = p2.payload
  31. def fail(self, message: str):
  32. raise AssertionError(message)
  33. if __name__ == "__main__":
  34. import sys
  35. if len(sys.argv) < 3:
  36. print("Usage: %s one.pcap other.pcap" % sys.argv[0])
  37. exit(0)
  38. try:
  39. PcapComparator().compare_files(sys.argv[1], sys.argv[2])
  40. print("The given pcaps are equal")
  41. except AssertionError as e:
  42. print("The given pcaps are not equal")
  43. print("Error message:", *e.args)
  44. exit(1)
  45. except Exception as e:
  46. print("During the comparison an unexpected error happened")
  47. print(type(e).__name__ + ":", *e.args)
  48. exit(1)