scapy.utils
General utility functions.
- scapy.utils.AutoArgparse(func: DecoratorCallable) None [source]
Generate an Argparse call from a function, then call this function.
Notes:
for the arguments to have a description, the sphinx docstring format must be used. See https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html
the arguments must be typed in Python (we ignore Sphinx-specific types) untyped arguments are ignored.
only types that would be supported by argparse are supported. The others are omitted.
- class scapy.utils.CLIUtil[source]
Bases:
object
Provides a Util class to easily create simple CLI tools in Scapy, that can still be used as an API.
- Doc:
override the ps1() function
register commands with the @CLIUtil.addcomment decorator
call the loop() function when ready
- classmethod addcommand(spaces: bool = False, globsupport: bool = False) Callable[[DecoratorCallable], DecoratorCallable] [source]
Decorator to register a command
- classmethod addcomplete(cmd: DecoratorCallable) Callable[[DecoratorCallable], DecoratorCallable] [source]
Decorator to register a command completor
- classmethod addoutput(cmd: DecoratorCallable) Callable[[DecoratorCallable], DecoratorCallable] [source]
Decorator to register a command output processor
- commands: Dict[str, Callable[[...], Any]] = {'backup': <function smbclient.backup>, 'cat': <function smbclient.cat>, 'cd': <function smbclient.cd>, 'get': <function smbclient.get>, 'lcd': <function smbclient.lcd>, 'lls': <function smbclient.lls>, 'ls': <function smbclient.ls>, 'put': <function smbclient.put>, 'rm': <function smbclient.rm>, 'shares': <function smbclient.shares>, 'use': <function smbclient.use>}
- commands_complete: Dict[str, Callable[[...], List[str]]] = {'cat': <function smbclient.cat_complete>, 'cd': <function smbclient.cd_complete>, 'get': <function smbclient.get_complete>, 'lcd': <function smbclient.lcd_complete>, 'ls': <function smbclient.ls_complete>, 'put': <function smbclient.put_complete>, 'rm': <function smbclient.rm_complete>, 'use': <function smbclient.use_complete>}
- commands_output: Dict[str, Callable[[...], str]] = {'cat': <function smbclient.cat_output>, 'cd': <function smbclient.cd_output>, 'get': <function smbclient.get_output>, 'lcd': <function smbclient.lcd_output>, 'lls': <function smbclient.lls_output>, 'ls': <function smbclient.ls_output>, 'shares': <function smbclient.shares_output>}
- class scapy.utils.ContextManagerCaptureOutput[source]
Bases:
object
Context manager that intercept the console’s output.
Example: >>> with ContextManagerCaptureOutput() as cmco: … print(“hey”) … assert cmco.get_output() == “hey”
- class scapy.utils.ContextManagerSubprocess(prog: str, suppress: bool = True)[source]
Bases:
object
Context manager that eases checking for unknown command, without crashing.
Example: >>> with ContextManagerSubprocess(“tcpdump”): >>> subprocess.Popen([“tcpdump”, “–version”]) ERROR: Could not execute tcpdump, is it installed?
- class scapy.utils.EDecimal(value='0', context=None)[source]
Bases:
Decimal
Extended Decimal
This implements arithmetic and comparison with float for backward compatibility
- class scapy.utils.ERFEthernetReader(filename: IO[bytes] | str)[source]
Bases:
PcapReader
- class scapy.utils.ERFEthernetReader_metaclass(name: Any, bases: str, dct: Any)[source]
Bases:
PcapReader_metaclass
- class scapy.utils.ERFEthernetWriter(filename: IO[bytes] | str, gz: bool = False, append: bool = False, sync: bool = False)[source]
Bases:
PcapWriter
A stream ERF Ethernet writer with more control than wrerf()
- write(pkt: _PacketIterable) None [source]
Writes a Packet, a SndRcvList object, or bytes to a ERF file.
- Parameters:
pkt (iterable[scapy.packet.Packet], scapy.packet.Packet) – Packet(s) to write (one record for each Packet)
- class scapy.utils.Enum_metaclass(name: Any, bases: str, dct: Any)[source]
Bases:
type
- element_class[source]
alias of
EnumElement
- class scapy.utils.GenericPcapWriter[source]
Bases:
object
- linktype: int
- nano = False
- write_packet(packet: bytes | Packet, sec: float | None = None, usec: int | None = None, caplen: int | None = None, wirelen: int | None = None) None [source]
Writes a single packet to the pcap file.
- Parameters:
packet (scapy.packet.Packet or bytes) – Packet, or bytes for a single packet
sec (float) – time the packet was captured, in seconds since epoch. If not supplied, defaults to now.
usec (int or long) – If
nano=True
, then number of nanoseconds after the second that the packet was captured. Ifnano=False
, then the number of microseconds after the second the packet was captured. Ifsec
is not specified, this value is ignored.caplen (int) – The length of the packet in the capture file. If not specified, uses
len(raw(packet))
.wirelen (int) – The length of the packet on the wire. If not specified, tries
packet.wirelen
, otherwise usescaplen
.
- Returns:
None
- Return type:
None
- class scapy.utils.GenericRawPcapWriter[source]
Bases:
GenericPcapWriter
- f: IO[bytes] | GzipFile = None
- header_present = False
- nano = False
- sync = False
- write(pkt: _PacketIterable | bytes) None [source]
Writes a Packet, a SndRcvList object, or bytes to a pcap file.
- Parameters:
pkt (iterable[scapy.packet.Packet], scapy.packet.Packet or bytes) – Packet(s) to write (one record for each Packet), or raw bytes to write (as one record).
- class scapy.utils.PcapNgReader(filename: IO[bytes] | str)[source]
Bases:
RawPcapNgReader
,PcapReader
- alternative[source]
alias of
PcapReader
- class scapy.utils.PcapNgWriter(filename: str)[source]
Bases:
RawPcapNgWriter
A stream pcapng writer with more control than wrpcapng()
- class scapy.utils.PcapReader(filename: IO[bytes] | str)[source]
Bases:
RawPcapReader
- alternative[source]
alias of
PcapNgReader
- read_all(count: int = -1) PacketList [source]
- class scapy.utils.PcapReader_metaclass(name: Any, bases: str, dct: Any)[source]
Bases:
type
Metaclass for (Raw)Pcap(Ng)Readers
- class scapy.utils.PcapWriter(filename: IO[bytes] | str, linktype: int | None = None, gz: bool = False, endianness: str = '', append: bool = False, sync: bool = False, nano: bool = False, snaplen: int = 65535, bufsz: int = 4096)[source]
Bases:
RawPcapWriter
A stream PCAP writer with more control than wrpcap()
- class scapy.utils.PeriodicSenderThread(sock: Any, pkt: _PacketIterable, interval: float = 0.5, ignore_exceptions: bool = True)[source]
Bases:
Thread
- class scapy.utils.RawPcapNgReader(filename: IO[bytes] | str)[source]
Bases:
RawPcapReader
A stateful pcapng reader. Each packet is returned as bytes.
- alternative[source]
alias of
RawPcapReader
- class scapy.utils.RawPcapNgWriter(filename: str)[source]
Bases:
GenericRawPcapWriter
A stream pcapng writer with more control than wrpcapng()
- class scapy.utils.RawPcapReader(filename: IO[bytes] | str)[source]
Bases:
object
A stateful pcap reader. Each packet is returned as a string
- class PacketMetadata(sec, usec, wirelen, caplen)[source]
Bases:
tuple
- caplen
Alias for field number 3
- sec
Alias for field number 0
- usec
Alias for field number 1
- wirelen
Alias for field number 2
- alternative[source]
alias of
RawPcapNgReader
- dispatch(callback: Callable[[Tuple[bytes, PacketMetadata]], Any]) None [source]
call the specified callback routine for each packet read
This is just a convenience function for the main loop that allows for easy launching of packet processing in a thread.
- nonblocking_socket = True
- static select(sockets: List[SuperSocket], remain: float | None = None) List[SuperSocket] [source]
- class scapy.utils.RawPcapWriter(filename: IO[bytes] | str, linktype: int | None = None, gz: bool = False, endianness: str = '', append: bool = False, sync: bool = False, nano: bool = False, snaplen: int = 65535, bufsz: int = 4096)[source]
Bases:
GenericRawPcapWriter
A stream PCAP writer with more control than wrpcap()
- scapy.utils.chexdump(p: Packet | AnyStr, dump: bool = False) str | None [source]
Build a per byte hexadecimal representation
Example
>>> chexdump(IP()) 0x45, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x7c, 0xe7, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01 # noqa: E501
- Parameters:
p – a Packet
dump – print the view if False
- Returns:
a String only if dump=True
- scapy.utils.colgen(*lstcol: Any, **kargs: Any) Iterator[Any] [source]
Returns a generator that mixes provided quantities forever trans: a function to convert the three arguments into a color. lambda x,y,z:(x,y,z) by default
- scapy.utils.corrupt_bits(data: str, p: float = 0.01, n: int | None = None) bytes [source]
Flip a given percentage (at least one bit) or number of bits from a string
- scapy.utils.corrupt_bytes(data: str, p: float = 0.01, n: int | None = None) bytes [source]
Corrupt a given percentage (at least one byte) or number of bytes from a string
- scapy.utils.decode_locale_str(x: bytes) str [source]
Decode bytes into a string using the system locale. Useful on Windows where it can be unusual (e.g. cp1252)
- scapy.utils.do_graph(graph: str, prog: str | None = None, format: str | None = None, target: IO[bytes] | str | None = None, type: str | None = None, string: bool | None = None, options: List[str] | None = None) str | None [source]
Processes graph description using an external software. This method is used to convert a graphviz format to an image.
- Parameters:
graph – GraphViz graph description
prog – which graphviz program to use
format – output type (svg, ps, gif, jpg, etc.), passed to dot’s “-T” option
string – if not None, simply return the graph string
target – filename or redirect. Defaults pipe to Imagemagick’s display program
options – options to be passed to prog
- scapy.utils.fletcher16_checkbytes(binbuf: bytes, offset: int) bytes [source]
Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string.
Including the bytes into the buffer (at the position marked by offset) the # noqa: E501 global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify # noqa: E501 the integrity of the buffer on the receiver side.
For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B. # noqa: E501
- scapy.utils.fletcher16_checksum(binbuf: bytes) int [source]
Calculates Fletcher-16 checksum of the given buffer.
Note: If the buffer contains the two checkbytes derived from the Fletcher-16 checksum # noqa: E501 the result of this function has to be 0. Otherwise the buffer has been corrupted. # noqa: E501
- scapy.utils.get_temp_dir(keep: bool = False) str [source]
Creates a temporary file, and returns its name.
- Parameters:
keep – If False (default), the directory will be recursively deleted when Scapy exits.
- Returns:
A full path to a temporary directory.
- scapy.utils.get_temp_file(keep, autoext, fd)[source]
- scapy.utils.get_temp_file(keep=False, autoext='', fd=False)
Creates a temporary file.
- Parameters:
keep – If False, automatically delete the file when Scapy exits.
autoext – Suffix to add to the generated file name.
fd – If True, this returns a file-like object with the temporary file opened. If False (default), this returns a file path.
- scapy.utils.get_terminal_width() int | None [source]
Get terminal width (number of characters) if in a window.
Notice: this will try several methods in order to support as many terminals and OS as possible.
- scapy.utils.hexdiff(a: Packet | AnyStr, b: Packet | AnyStr, algo: str | None = None, autojunk: bool = False) None [source]
Show differences between 2 binary strings, Packets…
- Available algorithms:
wagnerfischer: Use the Wagner and Fischer algorithm to compute the Levenstein distance between the strings then backtrack.
difflib: Use the difflib.SequenceMatcher implementation. This based on a modified version of the Ratcliff and Obershelp algorithm. This is much faster, but far less accurate. https://docs.python.org/3.8/library/difflib.html#difflib.SequenceMatcher
- Parameters:
a
b – The binary strings, packets… to compare
algo – Force the algo to be ‘wagnerfischer’ or ‘difflib’. By default, this is chosen depending on the complexity, optimistically preferring wagnerfischer unless really necessary.
autojunk – (difflib only) See difflib documentation.
- scapy.utils.hexdump(p: Packet | AnyStr, dump: bool = False) str | None [source]
Build a tcpdump like hexadecimal view
- Parameters:
p – a Packet
dump – define if the result must be printed or returned in a variable
- Returns:
a String only when dump=True
- scapy.utils.hexedit(pktlist: _PacketIterable) PacketList [source]
Run hexedit on a list of packets, then return the edited packets.
- scapy.utils.hexstr(p: Packet | AnyStr, onlyasc: int = 0, onlyhex: int = 0, color: bool = False) str [source]
Build a fancy tcpdump like hex from bytes.
- scapy.utils.human_size(x: int, fmt: str = '.1f') str [source]
Convert a size in octets to a human string representation
- scapy.utils.import_hexcap(input_string: str | None = None) bytes [source]
Imports a tcpdump like hexadecimal view
e.g: exported via hexdump() or tcpdump or wireshark’s “export as hex”
- Parameters:
input_string – String containing the hexdump input to parse. If None, read from standard input.
- scapy.utils.in4_cidr2mask(m: int) bytes [source]
Return the mask (bitstring) associated with provided length value. For instance if function is called on 20, return value is b’ÿÿð'.
- scapy.utils.in4_getnsmac(a: bytes) str [source]
Return the multicast mac address associated with provided IPv4 address. Passed address must be in network format.
- scapy.utils.in4_isaddrllallnodes(str: str) bool [source]
Returns True if address is the link-local all-nodes multicast address (224.0.0.1).
- scapy.utils.in4_isincluded(addr: str, prefix: str, mask: int) bool [source]
Returns True when ‘addr’ belongs to prefix/mask. False otherwise.
- scapy.utils.in4_ismaddr(str: str) bool [source]
Returns True if provided address in printable format belongs to allocated Multicast address space (224.0.0.0/4).
- scapy.utils.in4_ismgladdr(str: str) bool [source]
Returns True if address belongs to global multicast address space (224.0.1.0-238.255.255.255).
- scapy.utils.in4_ismlladdr(str: str) bool [source]
Returns True if address belongs to link-local multicast address space (224.0.0.0/24)
- scapy.utils.in4_ismlsaddr(str: str) bool [source]
Returns True if address belongs to limited scope multicast address space (239.0.0.0/8).
- scapy.utils.issubtype(C, B) bool [source]
Return whether C is a class and if it is a subclass of class B. When using a tuple as the second argument issubtype(X, (A, B, …)), is a shortcut for issubtype(X, A) or issubtype(X, B) or … (etc.).
- scapy.utils.linehexdump(p: Packet | AnyStr, onlyasc: int = 0, onlyhex: int = 0, dump: bool = False) str | None [source]
Build an equivalent view of hexdump() on a single line
Note that setting both onlyasc and onlyhex to 1 results in a empty output
- Parameters:
p – a Packet
onlyasc – 1 to display only the ascii view
onlyhex – 1 to display only the hexadecimal view
dump – print the view if False
- Returns:
a String only when dump=True
- scapy.utils.pretty_list(rtlst: List[Tuple[str | List[str], ...]], header: List[Tuple[str, ...]], sortBy: int | None = 0, borders: bool = False) str [source]
Pretty list to fit the terminal, and add header.
- Parameters:
rtlst – a list of tuples. each tuple contains a value which can be either a string or a list of string.
sortBy – the column id (starting with 0) which will be used for ordering
borders – whether to put borders on the table or not
- scapy.utils.rderf(filename: IO[bytes] | str, count: int = -1) PacketList [source]
Read a ERF file and return a packet list
- Parameters:
count – read only <count> packets
- scapy.utils.rdpcap(filename: IO[bytes] | str, count: int = -1) PacketList [source]
Read a pcap or pcapng file and return a packet list
- Parameters:
count – read only <count> packets
- scapy.utils.repr_hex(s: bytes) str [source]
Convert provided bitstring to a simple string of hex digits
- scapy.utils.strand(s1: bytes, s2: bytes) bytes [source]
Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2 must be of same length.
- scapy.utils.stror(s1: bytes, s2: bytes) bytes [source]
Returns the binary OR of the 2 provided strings s1 and s2. s1 and s2 must be of same length.
- scapy.utils.strrot(s1: bytes, count: int, right: bool = True) bytes [source]
Rotate the binary by ‘count’ bytes
- scapy.utils.strxor(s1: bytes, s2: bytes) bytes [source]
Returns the binary XOR of the 2 provided strings s1 and s2. s1 and s2 must be of same length.
- scapy.utils.tcpdump(pktlist: IO[bytes] | None | str | _PacketIterable = None, dump: bool = False, getfd: bool = False, args: List[str] | None = None, flt: str | None = None, prog: Any | None = None, getproc: bool = False, quiet: bool = False, use_tempfile: Any | None = None, read_stdin_opts: Any | None = None, linktype: Any | None = None, wait: bool = True, _suppress: bool = False) Any [source]
Run tcpdump or tshark on a list of packets.
When using
tcpdump
on OSX (prog == conf.prog.tcpdump
), this uses a temporary file to store the packets. This works around a bug in Apple’s version oftcpdump
: http://apple.stackexchange.com/questions/152682/Otherwise, the packets are passed in stdin.
This function can be explicitly enabled or disabled with the
use_tempfile
parameter.When using
wireshark
, it will be called with-ki -
to start immediately capturing packets from stdin.Otherwise, the command will be run with
-r -
(which is correct fortcpdump
andtshark
).This can be overridden with
read_stdin_opts
. This has no effect whenuse_tempfile=True
, or otherwise reading packets from a regular file.- Parameters:
pktlist – a Packet instance, a PacketList instance or a list of Packet instances. Can also be a filename (as a string), an open file-like object that must be a file format readable by tshark (Pcap, PcapNg, etc.) or None (to sniff)
flt – a filter to use with tcpdump
dump – when set to True, returns a string instead of displaying it.
getfd – when set to True, returns a file-like object to read data from tcpdump or tshark from.
getproc – when set to True, the subprocess.Popen object is returned
args – arguments (as a list) to pass to tshark (example for tshark: args=[“-T”, “json”]).
prog – program to use (defaults to tcpdump, will work with tshark)
quiet – when set to True, the process stderr is discarded
use_tempfile – When set to True, always use a temporary file to store packets. When set to False, pipe packets through stdin. When set to None (default), only use a temporary file with
tcpdump
on OSX.read_stdin_opts – When set, a list of arguments needed to capture from stdin. Otherwise, attempts to guess.
linktype – A custom DLT value or name, to overwrite the default values.
wait – If True (default), waits for the process to terminate before returning to Scapy. If False, the process will be detached to the background. If dump, getproc or getfd is True, these have the same effect as
wait=False
.
Examples:
>>> tcpdump([IP()/TCP(), IP()/UDP()]) reading from file -, link-type RAW (Raw IP) 16:46:00.474515 IP 127.0.0.1.20 > 127.0.0.1.80: Flags [S], seq 0, win 8192, length 0 # noqa: E501 16:46:00.475019 IP 127.0.0.1.53 > 127.0.0.1.53: [|domain] >>> tcpdump([IP()/TCP(), IP()/UDP()], prog=conf.prog.tshark) 1 0.000000 127.0.0.1 -> 127.0.0.1 TCP 40 20->80 [SYN] Seq=0 Win=8192 Len=0 # noqa: E501 2 0.000459 127.0.0.1 -> 127.0.0.1 UDP 28 53->53 Len=0
To get a JSON representation of a tshark-parsed PacketList(), one can:
>>> import json, pprint >>> json_data = json.load(tcpdump(IP(src="217.25.178.5", ... dst="45.33.32.156"), ... prog=conf.prog.tshark, ... args=["-T", "json"], ... getfd=True)) >>> pprint.pprint(json_data) [{u'_index': u'packets-2016-12-23', u'_score': None, u'_source': {u'layers': {u'frame': {u'frame.cap_len': u'20', u'frame.encap_type': u'7', [...] }, u'ip': {u'ip.addr': u'45.33.32.156', u'ip.checksum': u'0x0000a20d', [...] u'ip.ttl': u'64', u'ip.version': u'4'}, u'raw': u'Raw packet data'}}, u'_type': u'pcap_file'}] >>> json_data[0]['_source']['layers']['ip']['ip.ttl'] u'64'
- scapy.utils.tdecode(pktlist: IO[bytes] | None | str | _PacketIterable, args: List[str] | None = None, **kwargs: Any) Any [source]
Run tshark on a list of packets.
- Parameters:
args – If not specified, defaults to
tshark -V
.
See
tcpdump()
for more parameters.
- scapy.utils.wireshark(pktlist: List[Packet], wait: bool = False, **kwargs: Any) Any | None [source]
Runs Wireshark on a list of packets.
See
tcpdump()
for more parameter description.Note: this defaults to wait=False, to run Wireshark in the background.
- scapy.utils.wrerf(filename: IO[bytes] | str, pkt: _PacketIterable, *args: Any, **kargs: Any) None [source]
Write a list of packets to a ERF file
- Parameters:
filename – the name of the file to write packets to, or an open, writable file-like object. The file descriptor will be closed at the end of the call, so do not use an object you do not want to close (e.g., running wrerf(sys.stdout, []) in interactive mode will crash Scapy).
gz – set to 1 to save a gzipped capture
append – append packets to the capture file instead of truncating it
sync – do not bufferize writes to the capture file
- scapy.utils.wrpcap(filename: IO[bytes] | str, pkt: _PacketIterable, *args: Any, **kargs: Any) None [source]
Write a list of packets to a pcap file
- Parameters:
filename – the name of the file to write packets to, or an open, writable file-like object. The file descriptor will be closed at the end of the call, so do not use an object you do not want to close (e.g., running wrpcap(sys.stdout, []) in interactive mode will crash Scapy).
gz – set to 1 to save a gzipped capture
linktype – force linktype value
endianness – “<” or “>”, force endianness
sync – do not bufferize writes to the capture file
- scapy.utils.wrpcapng(filename: str, pkt: _PacketIterable) None [source]
Write a list of packets to a pcapng file
- Parameters:
filename – the name of the file to write packets to, or an open, writable file-like object. The file descriptor will be closed at the end of the call, so do not use an object you do not want to close (e.g., running wrpcapng(sys.stdout, []) in interactive mode will crash Scapy).
pkt – packets to write