scapy.packet

Packet class

Provides:
  • the default Packet classes

  • binding mechanisms

  • fuzz() method

  • exploration methods: explore() / ls()

class scapy.packet.NoPayload(_pkt, /)[源代码]

基类:Packet

add_parent(parent: Any) None[源代码]
add_payload(payload: Packet | bytes) NoReturn[源代码]
add_underlayer(underlayer: Any) None[源代码]
aliastypes
answers(other: Packet) bool[源代码]
build() bytes[源代码]
build_done(p: bytes) bytes[源代码]
build_padding() bytes[源代码]
build_ps(internal: int = 0) Tuple[bytes, List[Any]][源代码]
clear_cache() None[源代码]
command() str[源代码]
copy() NoPayload[源代码]
delfieldval(attr: str) NoReturn[源代码]
dissection_done(pkt: Packet) None[源代码]
do_build() bytes[源代码]
fragment(*args: Any, **kargs: Any) List[Packet][源代码]
getfield_and_val(attr: str) NoReturn[源代码]
getfieldval(attr: str) NoReturn[源代码]
getlayer(cls: int | Type[Packet] | str, nb: int = 1, _track: List[int] | None = None, _subclass: bool | None = None, **flt: Any) Packet | None[源代码]
hashret() bytes[源代码]
haslayer(cls: Type[Packet] | str, _subclass: bool | None = None) int[源代码]
hide_defaults() None[源代码]
lastlayer(layer: Packet | None = None) Packet[源代码]
layers() List[Type[Packet]][源代码]
remove_parent(other: Packet) None[源代码]
remove_payload() None[源代码]
remove_underlayer(other: Packet) None[源代码]
route() Tuple[None, None, None][源代码]
setfieldval(attr: str, val: Any) NoReturn[源代码]
show(dump: bool = False, indent: int = 3, lvl: str = '', label_lvl: str = '') None[源代码]
sprintf(fmt: str, relax: int = 1) str[源代码]
class scapy.packet.Packet(_pkt, /)[源代码]

基类:BasePacket, _CanvasDumpExtended

add_parent(parent: Packet) None[源代码]

Set packet parent. When packet is an element in PacketListField, parent field would point to the list owner packet.

add_payload(payload: Packet | bytes) None[源代码]
add_underlayer(underlayer: Packet) None[源代码]
aliastypes
answers(other: Packet) int[源代码]

DEV: true if self is an answer from other

build() bytes[源代码]

Create the current layer

返回:

string of the packet with the payload

build_done(p: bytes) bytes[源代码]
build_padding() bytes[源代码]
build_ps(internal: int = 0) Tuple[bytes, List[Tuple[Packet, List[Tuple[Any, Any, bytes]]]]][源代码]
canvas_dump(layer_shift: int = 0, rebuild: int = 1) pyx.canvas.canvas[源代码]
class_default_fields
class_default_fields_ref
class_dont_cache
class_fieldtype
class_packetfields
clear_cache() None[源代码]

Clear the raw packet cache for the field and all its subfields

clone_with(payload: Any | None = None, **kargs: Any) Any[源代码]
command() str[源代码]

Returns a string representing the command you have to type to obtain the same packet

comment: bytes | None
copy() Self[源代码]

Returns a deep copy of the instance.

copy_field_value(fieldname: str, value: Any) Any[源代码]
copy_fields_dict(fields: _T) _T[源代码]
decode_payload_as(cls: Type[Packet]) None[源代码]

Reassembles the payload and decode it using another packet class

default_fields: Dict[str, Any]
default_payload_class(payload: bytes) Type[Packet][源代码]

DEV: Returns the default payload class if nothing has been found by the guess_payload_class() method.

参数:

payload (str) -- the layer's payload

返回:

the default payload class define inside the configuration file

delfieldval(attr: str) None[源代码]
deprecated_fields: Dict[str, Tuple[str, str]] = {}
direction: int | None
display(*args: Any, **kargs: Any) None[源代码]

Deprecated. Use show() method.

dissect(s: bytes) None[源代码]
dissection_done(pkt: Packet) None[源代码]

DEV: will be called after a dissection is completed

do_build() bytes[源代码]

Create the default version of the layer

返回:

a string of the packet with the payload

do_build_payload() bytes[源代码]

Create the default version of the payload layer

返回:

a string of payload layer

do_build_ps() Tuple[bytes, List[Tuple[Packet, List[Tuple[Field[Any, Any], str, bytes]]]]][源代码]
do_dissect(s: bytes) bytes[源代码]
do_dissect_payload(s: bytes) None[源代码]

Perform the dissection of the layer's payload

参数:

s (str) -- the raw layer

do_init_cached_fields() None[源代码]

Initialize each fields of the fields_desc dict, or use the cached fields information

do_init_fields(flist: Sequence[Field[Any, Any] | _FieldContainer]) None[源代码]

Initialize each fields of the fields_desc dict

explicit
extract_padding(s: bytes) Tuple[bytes, bytes | None][源代码]

DEV: to be overloaded to extract current layer's padding.

参数:

s (str) -- the current layer

返回:

a couple of strings (actual layer, padding)

fields: Dict[str, Any]
fields_desc
fieldtype: Dict[str, Field[Any, Any] | _FieldContainer]
firstlayer() Packet[源代码]
fragment(*args: Any, **kargs: Any) List[Packet][源代码]
classmethod from_hexcap() Packet[源代码]
get_field(fld: str) Field[Any, Any] | _FieldContainer[源代码]

DEV: returns the field instance from the name of the field

getfield_and_val(attr: str) Tuple[Field[Any, Any] | _FieldContainer, Any][源代码]
getfieldval(attr: str) Any[源代码]
getlayer(cls: int | Type[Packet] | str, nb: int = 1, _track: List[int] | None = None, _subclass: bool | None = None, **flt: Any) Packet | None[源代码]

Return the nb^th layer that is an instance of cls, matching flt values.

guess_payload_class(payload: bytes) Type[Packet][源代码]

DEV: Guesses the next payload class from layer bonds. Can be overloaded to use a different mechanism.

参数:

payload (str) -- the layer's payload

返回:

the payload class

hashret() bytes[源代码]

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[源代码]

true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax.

hide_defaults() None[源代码]

Removes fields' values that are the same as default values.

init_fields() None[源代码]

Initialize each fields of the fields_desc dict

iterpayloads() Iterator[Packet][源代码]

Used to iter through the payloads of a Packet. Useful for DNS or 802.11 for instance.

lastlayer(layer: Packet | None = None) Packet[源代码]

Returns the uppest layer of the packet

layers() List[Type[Packet]][源代码]

returns a list of layer classes (including subclasses) in this packet

classmethod lower_bonds() None[源代码]
match_subclass = False
mysummary() str[源代码]

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
overload_fields: Dict[Type[Packet], Dict[str, Any]]
overloaded_fields: Dict[str, Any]
packetfields: List[Field[Any, Any] | _FieldContainer]
parent
payload: Packet
payload_guess
post_build(pkt: bytes, pay: bytes) bytes[源代码]

DEV: called right after the current layer is build.

参数:
  • pkt (str) -- the current packet (build by self_build function)

  • pay (str) -- the packet payload (build by do_build_payload function)

返回:

a string of the packet with the payload

post_dissect(s: bytes) bytes[源代码]

DEV: is called right after the current layer has been dissected

post_dissection(pkt: Packet) None[源代码]

DEV: is called after the dissection of the whole packet

post_transforms
pre_dissect(s: bytes) bytes[源代码]

DEV: is called right before the current layer is dissected

prepare_cached_fields(flist: Sequence[Field[Any, Any] | _FieldContainer]) None[源代码]

Prepare the cached fields of the fields_desc dict

raw_packet_cache: bytes | None
raw_packet_cache_fields: Dict[str, Any] | None
remove_parent(other: Packet) None[源代码]

Remove packet parent. When packet is an element in PacketListField, parent field would point to the list owner packet.

remove_payload() None[源代码]
remove_underlayer(other: Packet) None[源代码]
route() Tuple[str | None, str | None, str | None][源代码]
self_build() bytes[源代码]

Create the default layer regarding fields_desc dict

参数:

field_pos_list --

sent_time: EDecimal | float | None
setfieldval(attr: str, val: Any) None[源代码]
show(dump: bool = False, indent: int = 3, lvl: str = '', label_lvl: str = '') Any | None[源代码]

Prints or returns (when "dump" is true) a hierarchical view of the packet.

参数:
  • 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

返回:

return a hierarchical view if dump, else print it

show2(dump: bool = False, indent: int = 3, lvl: str = '', label_lvl: str = '') Any | None[源代码]

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.)

参数:
  • 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

返回:

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[源代码]

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%

参数:

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 "%)".

summary(intern: int = 0) str[源代码]

Prints a one line summary of a packet.

time: EDecimal | float
underlayer
classmethod upper_bonds() None[源代码]
wirelen: int | None
class scapy.packet.Padding(_pkt, /, *, load=b'')[源代码]

基类:Raw

aliastypes
build_padding() bytes[源代码]
fields_desc
Display RFC-like schema
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|              LOAD             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

                           Fig. Padding                           
Padding fields

load

StrField

b''

self_build(field_pos_list: Any | None = None) bytes[源代码]
class scapy.packet.Raw(_pkt, /, *, load=b'')[源代码]

基类:Packet

aliastypes
answers(other: Packet) int[源代码]
fields_desc
Display RFC-like schema
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|              LOAD             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

                             Fig. Raw                             
Raw fields

load

StrField

b''

mysummary() str[源代码]
scapy.packet.bind_bottom_up(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None[源代码]

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[源代码]

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[源代码]

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[源代码]

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

示例

>>> 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[源代码]

Transform a layer into a fuzzy layer by replacing some default values by random objects.

参数:

p -- the Packet instance to fuzz

返回:

the fuzzed packet.

scapy.packet.ls(obj: str | Packet | Type[Packet] | None = None, case_sensitive: bool = False, verbose: bool = False) None[源代码]

List available layers, or infos on a given layer class or name.

参数:
  • 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[源代码]

Generate an RFC-like representation of a packet def.

参数:
  • 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[源代码]

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[源代码]

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)

scapy.packet.split_top_down(lower: Type[Packet], upper: Type[Packet], __fval: Any | None = None, **fval: Any) None[源代码]

This call un-links an association that was made using bind_top_down. Have a look at help(bind_top_down)