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")))
@vadimszzz
Copy link

layer_tmp_name = str(layer.__dict__["aliastypes"][0]

KeyError: 'aliastypes'

@vadimszzz
Copy link

In anaconda 3.5, jupyter cell, when I call the function with a packet

> KeyError                                  Traceback (most recent call last)
> <ipython-input-64-0bfed3ab77b3> in <module>
> ----> 1 pkg_to_json(pfh[1])
> 
> <ipython-input-63-50653fd7dd41> in pkg_to_json(pkg)
>      27 
>      28                         # Get layer name
> ---> 29                         layer_tmp_name = str(layer.__dict__["aliastypes"][0])
>      30                         layer_start_pos = layer_tmp_name.rfind(".") + 1
>      31                         layer_name = layer_tmp_name[layer_start_pos:-2].lower()
> 
> KeyError: 'aliastypes'

am I missing something?

Scapy changed API

@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