scapy.packet
Packet class
- Provides:
the default Packet classes
binding mechanisms
fuzz() method
exploration methods: explore() / ls()
- class scapy.packet.NoPayload(_pkt, /)[source]
Bases:
Packet
- aliastypes
- class scapy.packet.Packet(_pkt, /)[source]
Bases:
BasePacket
,_CanvasDumpExtended
- add_parent(parent: Packet) None [source]
Set packet parent. When packet is an element in PacketListField, parent field would point to the list owner packet.
- aliastypes
- build_ps(internal: int = 0) Tuple[bytes, List[Tuple[Packet, List[Tuple[Any, Any, bytes]]]]] [source]
- class_default_fields
- class_default_fields_ref
- class_dont_cache
- class_fieldtype
- class_packetfields
- command() str [source]
Returns a string representing the command you have to type to obtain the same packet
- comment: bytes | None
- decode_payload_as(cls: Type[Packet]) None [source]
Reassembles the payload and decode it using another packet class
- default_fields: Dict[str, Any]
- default_payload_class(payload: bytes) Type[Packet] [source]
DEV: Returns the default payload class if nothing has been found by the guess_payload_class() method.
- Parameters:
payload (str) – the layer’s payload
- Returns:
the default payload class define inside the configuration file
- deprecated_fields: Dict[str, Tuple[str, str]] = {}
- direction: int | None
- do_build() bytes [source]
Create the default version of the layer
- Returns:
a string of the packet with the payload
- do_build_payload() bytes [source]
Create the default version of the payload layer
- Returns:
a string of payload layer
- do_dissect_payload(s: bytes) None [source]
Perform the dissection of the layer’s payload
- Parameters:
s (str) – the raw layer
- do_init_cached_fields(for_dissect_only: bool = False) None [source]
Initialize each fields of the fields_desc dict, or use the cached fields information
- do_init_fields(flist: Sequence[Field[Any, Any] | _FieldContainer]) None [source]
Initialize each fields of the fields_desc dict
- explicit
- extract_padding(s: bytes) Tuple[bytes, bytes | None] [source]
DEV: to be overloaded to extract current layer’s padding.
- Parameters:
s (str) – the current layer
- Returns:
a couple of strings (actual layer, padding)
- fields: Dict[str, Any]
- fields_desc
- get_field(fld: str) Field[Any, Any] | _FieldContainer [source]
DEV: returns the field instance from the name of the field
- getlayer(cls: int | Type[Packet] | str, nb: int = 1, _track: List[int] | None = None, _subclass: bool | None = None, **flt: Any) Packet | None [source]
Return the nb^th layer that is an instance of cls, matching flt values.
- guess_payload_class(payload: bytes) Type[Packet] [source]
DEV: Guesses the next payload class from layer bonds. Can be overloaded to use a different mechanism.
- Parameters:
payload (str) – the layer’s payload
- Returns:
the payload class
- hashret() bytes [source]
DEV: returns a string that has the same value for a request and its answer.
- haslayer(cls: Type[Packet] | str, _subclass: bool | None = None) int [source]
true if self has a layer that is an instance of cls. Superseded by “cls in self” syntax.
- init_fields(for_dissect_only: bool = False) None [source]
Initialize each fields of the fields_desc dict
- iterpayloads() Iterator[Packet] [source]
Used to iter through the payloads of a Packet. Useful for DNS or 802.11 for instance.
- json() str [source]
Returns a JSON representing the packet.
Please note that this cannot be used for bijective usage: data loss WILL occur, so it will not make sense to try to rebuild the packet from the output. This must only be used for a grepping/displaying purpose.
- layers() List[Type[Packet]] [source]
returns a list of layer classes (including subclasses) in this packet
- match_subclass = False
- mysummary() str [source]
DEV: can be overloaded to return a string that summarizes the layer. Only one mysummary() is used in a whole packet summary: the one of the upper layer, # noqa: E501 except if a mysummary() also returns (as a couple) a list of layers whose # noqa: E501 mysummary() must be called if they are present.
- name
- original
- overloaded_fields: Dict[str, Any]
- parent
- payload_guess
- post_build(pkt: bytes, pay: bytes) bytes [source]
DEV: called right after the current layer is build.
- Parameters:
pkt (str) – the current packet (build by self_build function)
pay (str) – the packet payload (build by do_build_payload function)
- Returns:
a string of the packet with the payload
- post_dissect(s: bytes) bytes [source]
DEV: is called right after the current layer has been dissected
- post_transforms
- prepare_cached_fields(flist: Sequence[Field[Any, Any] | _FieldContainer]) None [source]
Prepare the cached fields of the fields_desc dict
- process_information: Dict[str, Any] | None
- raw_packet_cache: bytes | None
- raw_packet_cache_fields: Dict[str, Any] | None
- remove_parent(other: Packet) None [source]
Remove packet parent. When packet is an element in PacketListField, parent field would point to the list owner packet.
- self_build() bytes [source]
Create the default layer regarding fields_desc dict
- Parameters:
field_pos_list
- show(dump: bool = False, indent: int = 3, lvl: str = '', label_lvl: str = '') Any | None [source]
Prints or returns (when “dump” is true) a hierarchical view of the packet.
- Parameters:
dump – determine if it prints or returns the string value
indent (int) – the size of indentation for each layer
lvl (str) – additional information about the layer lvl
label_lvl (str) – additional information about the layer fields
- Returns:
return a hierarchical view if dump, else print it
- show2(dump: bool = False, indent: int = 3, lvl: str = '', label_lvl: str = '') Any | None [source]
Prints or returns (when “dump” is true) a hierarchical view of an assembled version of the packet, so that automatic fields are calculated (checksums, etc.)
- Parameters:
dump – determine if it prints or returns the string value
indent (int) – the size of indentation for each layer
lvl (str) – additional information about the layer lvl
label_lvl (str) – additional information about the layer fields
- Returns:
return a hierarchical view if dump, else print it
- show_indent = 1
- show_summary = True
- sniffed_on: NetworkInterface | str | None
- sprintf(format[, relax=1]) str [source]
Where format is a string that can include directives. A directive begins and ends by % and has the following format:
%[fmt[r],][cls[:nb].]field%
- Parameters:
fmt –
is a classic printf directive, “r” can be appended for raw substitution: (ex: IP.flags=0x18 instead of SA), nb is the number of the layer (ex: for IP/IP packets, IP:2.src is the src of the upper IP layer). Special case : “%.time%” is the creation time. Ex:
p.sprintf( "%.time% %-15s,IP.src% -> %-15s,IP.dst% %IP.chksum% " "%03xr,IP.proto% %r,TCP.flags%" )
Moreover, the format string can include conditional statements. A conditional statement looks like : {layer:string} where layer is a layer name, and string is the string to insert in place of the condition if it is true, i.e. if layer is present. If layer is preceded by a “!”, the result is inverted. Conditions can be imbricated. A valid statement can be:
p.sprintf("This is a{TCP: TCP}{UDP: UDP}{ICMP:n ICMP} packet") p.sprintf("{IP:%IP.dst% {ICMP:%ICMP.type%}{TCP:%TCP.dport%}}")
A side effect is that, to obtain “{” and “}” characters, you must use “%(” and “%)”.
- stop_dissection_after
- underlayer
- wirelen: int | None
- class scapy.packet.Padding(_pkt, /, *, load=b'')[source]
Bases:
Raw
- aliastypes
- class scapy.packet.Raw(_pkt, /, *, load=b'')[source]
Bases:
Packet
- aliastypes
- scapy.packet.bind_bottom_up(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None [source]
Bind 2 layers for dissection. The upper layer will be chosen for dissection on top of the lower layer, if ALL the passed arguments are validated. If multiple calls are made with the same layers, the last one will be used as default.
- ex:
>>> bind_bottom_up(Ether, SNAP, type=0x1234) >>> Ether(b'\xff\xff\xff\xff\xff\xff\xd0P\x99V\xdd\xf9\x124\x00\x00\x00\x00\x00') # noqa: E501 <Ether dst=ff:ff:ff:ff:ff:ff src=d0:50:99:56:dd:f9 type=0x1234 |<SNAP OUI=0x0 code=0x0 |>> # noqa: E501
- scapy.packet.bind_layers(lower: Type[Packet], upper: Type[Packet], __fval: Dict[str, int] | None = None, **fval: Any) None [source]
Bind 2 layers on some specific fields’ values.
It makes the packet being built and dissected when the arguments are present.
This function calls both bind_bottom_up and bind_top_down, with all passed arguments.
- Please have a look at their docs:
help(bind_bottom_up)
help(bind_top_down)
- scapy.packet.bind_top_down(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None [source]
Bind 2 layers for building. When the upper layer is added as a payload of the lower layer, all the arguments will be applied to them.
- ex:
>>> bind_top_down(Ether, SNAP, type=0x1234) >>> Ether()/SNAP() <Ether type=0x1234 |<SNAP |>>
- scapy.packet.explore(layer: str | None = None) None [source]
Function used to discover the Scapy layers and protocols. It helps to see which packets exists in contrib or layer files.
- params:
- layer: If specified, the function will explore the layer. If not,
the GUI mode will be activated, to browse the available layers
Examples
>>> explore() # Launches the GUI >>> explore("dns") # Explore scapy.layers.dns >>> explore("http2") # Explore scapy.contrib.http2 >>> explore(scapy.layers.bluetooth4LE)
Note: to search a packet by name, use ls(“name”) rather than explore.
- scapy.packet.fuzz(p: _P, _inplace: int = 0) _P [source]
Transform a layer into a fuzzy layer by replacing some default values by random objects.
- Parameters:
p – the Packet instance to fuzz
- Returns:
the fuzzed packet.
- scapy.packet.ls(obj: str | Packet | Type[Packet] | None = None, case_sensitive: bool = False, verbose: bool = False) None [source]
List available layers, or infos on a given layer class or name.
- Parameters:
obj – Packet / packet name to use
case_sensitive – if obj is a string, is it case sensitive?
verbose
- scapy.packet.rfc(cls: Type[Packet], ret: bool = False, legend: bool = True) str | None [source]
Generate an RFC-like representation of a packet def.
- Parameters:
cls – the Packet class
ret – return the result instead of printing (def. False)
legend – show text under the diagram (default True)
Ex:
>>> rfc(Ether)
- scapy.packet.split_bottom_up(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None [source]
This call un-links an association that was made using bind_bottom_up. Have a look at help(bind_bottom_up)
- scapy.packet.split_layers(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None [source]
Split 2 layers previously bound. This call un-links calls bind_top_down and bind_bottom_up. It is the opposite of # noqa: E501 bind_layers.
- Please have a look at their docs:
help(split_bottom_up)
help(split_top_down)