Skip to content

Instantly share code, notes, and snippets.

@cr0hn
Last active September 21, 2023 17:43
Show Gist options
  • Save cr0hn/1b0c2e672cd0721d3a07 to your computer and use it in GitHub Desktop.
Save cr0hn/1b0c2e672cd0721d3a07 to your computer and use it in GitHub Desktop.
Transform a Scapy packet to JSON data
# -*- coding: utf-8 -*-
"""
This file contains the function to convert a Scapy packet to JSON representation
"""
from __future__ import print_function
import json
from collections import defaultdict
__author__ = "Daniel Garcia (cr0hn) - @ggdaniel"
def pkg_to_json(pkg):
"""
This function convert a Scapy packet to JSON
:param pkg: A scapy package
:type pkg: objects
:return: A JSON data
:rtype: dict()
"""
results = defaultdict(dict)
try:
for index in range(50):
layer = pkg[index]
# Get layer name
layer_tmp_name = str(layer.__dict__["aliastypes"][0])
layer_start_pos = layer_tmp_name.rfind(".") + 1
layer_name = layer_tmp_name[layer_start_pos:-2].lower()
# Get the layer info
tmp_t = {}
for x, y in layer.__dict__["default_fields"].items():
if y and not isinstance(y, (str, int, long, float, list, dict)):
tmp_t[x].update(pkg_to_json(y))
else:
tmp_t[x] = y
results[layer_name] = tmp_t
try:
tmp_t = {}
for x, y in layer.__dict__["fields"].items():
if y and not isinstance(y, (str, int, long, float, list, dict)):
tmp_t[x].update(pkg_to_json(y))
else:
tmp_t[x] = y
results[layer_name] = tmp_t
except KeyError:
# No custom fields
pass
except IndexError:
# Package finish -> do nothing
pass
return json.dumps(results)
if __name__ == '__main__':
from scapy.all import IP, TCP, DNS, DNSQR, UDP
# print(pkg_to_json(IP(dst="8.8.8.8")/TCP(dport=80)/"hello World"))
print(pkg_to_json(IP(dst="8.8.8.8")/UDP(dport=53)/DNS()/DNSQR(qname="terra.es")))
@ble55edboi100
Copy link

where can I upload code to a json file? I'm uneducated in this department

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment