scapy.utils
General utility functions.
- class scapy.utils.ContextManagerCaptureOutput
Bases:
object
Context manager that intercept the console’s output.
Example: >>> with ContextManagerCaptureOutput() as cmco: … print(“hey”) … assert cmco.get_output() == “hey”
- get_output(eval_bytes=False)
- class scapy.utils.ContextManagerSubprocess(prog, suppress=True)
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)
Bases:
decimal.Decimal
Extended Decimal
This implements arithmetic and comparison with float for backward compatibility
- class scapy.utils.EnumElement(key, value)
Bases:
object
- class scapy.utils.Enum_metaclass(name, bases, dct)
Bases:
type
- element_class
alias of
scapy.utils.EnumElement
- get(attr, val=None)
- class scapy.utils.PcapNgReader(filename)
Bases:
scapy.utils.RawPcapNgReader
- alternative
alias of
scapy.utils.PcapReader
- read_all(count=- 1)
- read_packet(size=65535)
- recv(size=65535)
- class scapy.utils.PcapReader(filename)
Bases:
scapy.utils.RawPcapReader
- alternative
alias of
scapy.utils.PcapNgReader
- read_all(count=- 1)
- read_packet(size=65535)
- recv(size=65535)
- class scapy.utils.PcapReader_metaclass(name, bases, dct)
Bases:
type
Metaclass for (Raw)Pcap(Ng)Readers
- static open(filename)
Open (if necessary) filename, and read the magic.
- class scapy.utils.PcapWriter(filename, linktype=None, gz=False, endianness='', append=False, sync=False, nano=False, snaplen=65535)
Bases:
scapy.utils.RawPcapWriter
A stream PCAP writer with more control than wrpcap()
- class scapy.utils.PeriodicSenderThread(sock, pkt, interval=0.5)
Bases:
threading.Thread
- run()
- stop()
- class scapy.utils.RawPcapNgReader(filename)
Bases:
scapy.utils.RawPcapReader
A stateful pcapng reader. Each packet is returned as bytes.
- class PacketMetadata(linktype, tsresol, tshigh, tslow, wirelen)
Bases:
tuple
- linktype
Alias for field number 0
- tshigh
Alias for field number 2
- tslow
Alias for field number 3
- tsresol
Alias for field number 1
- wirelen
Alias for field number 4
- alternative
alias of
scapy.utils.RawPcapReader
- read_block_epb(block, size)
Enhanced Packet Block
- read_block_idb(block, _)
Interface Description Block
- read_block_pkt(block, size)
(Obsolete) Packet Block
- read_block_spb(block, size)
Simple Packet Block
- read_options(options)
Section Header Block
- read_packet(size=65535)
Read blocks until it reaches either EOF or a packet, and returns None or (packet, (linktype, sec, usec, wirelen)), where packet is a string.
- class scapy.utils.RawPcapReader(filename)
Bases:
object
A stateful pcap reader. Each packet is returned as a string
- class PacketMetadata(sec, usec, wirelen, caplen)
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
alias of
scapy.utils.RawPcapNgReader
- close()
- dispatch(callback)
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.
- fileno()
- next()
implement the iterator protocol on a set of packets in a pcap file pkt is a tuple (pkt_data, pkt_metadata) as defined in RawPcapReader.read_packet()
- nonblocking_socket = True
- read_all(count=- 1)
return a list of all packets in the pcap file
- read_packet(size=65535)
return a single packet read from the file as a tuple containing (pkt_data, pkt_metadata)
raise EOFError when no more packets are available
- recv(size=65535)
Emulate a socket
- static select(sockets, remain=None)
- class scapy.utils.RawPcapWriter(filename, linktype=None, gz=False, endianness='', append=False, sync=False, nano=False, snaplen=65535)
Bases:
object
A stream PCAP writer with more control than wrpcap()
- close()
- fileno()
- flush()
- write(pkt)
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.SingleConversationSocket(o)
Bases:
object
- send(x)
- sr(*args, **kargs)
- sr1(*args, **kargs)
- scapy.utils.atol(x)
- scapy.utils.binrepr(val)
- scapy.utils.checksum(pkt)
- scapy.utils.checksum_endian_transform(chk)
- scapy.utils.chexdump(x, dump=False)
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
x – a Packet
dump – print the view if False
- Returns
a String only if dump=True
- scapy.utils.colgen(*lstcol, **kargs)
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(s, p=0.01, n=None)
Flip a given percentage (at least one bit) or number of bits from a string
- scapy.utils.corrupt_bytes(s, p=0.01, n=None)
Corrupt a given percentage (at least one byte) or number of bytes from a string
- scapy.utils.do_graph(graph, prog=None, format=None, target=None, type=None, string=None, options=None)
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.export_object(obj)
- scapy.utils.fletcher16_checkbytes(binbuf, offset)
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)
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=False)
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=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()
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(x, y)
Show differences between 2 binary strings
- scapy.utils.hexdump(x, dump=False)
Build a tcpdump like hexadecimal view
- Parameters
x – 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)
Run hexedit on a list of packets, then return the edited packets.
- scapy.utils.hexstr(x, onlyasc=0, onlyhex=0, color=False)
Build a fancy tcpdump like hex from bytes.
- scapy.utils.import_hexcap(input_string=None)
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.import_object(obj=None)
- scapy.utils.incremental_label(label='tag%05i', start=0)
- scapy.utils.issubtype(C, B) bool
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.itom(x)
- scapy.utils.lhex(x)
- scapy.utils.linehexdump(x, onlyasc=0, onlyhex=0, dump=False)
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
x – 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.load_object(fname)
unpickle a Python object
- scapy.utils.long_converter(s)
- scapy.utils.ltoa(x)
- scapy.utils.mac2str(mac)
- scapy.utils.make_lined_table(*args, **kargs)
- scapy.utils.make_table(*args, **kargs)
- scapy.utils.make_tex_table(*args, **kargs)
- scapy.utils.pretty_list(rtlst, header, sortBy=0, borders=False)
Pretty list to fit the terminal, and add header
- scapy.utils.randstring(length)
Returns a random string of length (length >= 0)
- scapy.utils.rdpcap(filename, count=- 1)
Read a pcap or pcapng file and return a packet list
- Parameters
count – read only <count> packets
- scapy.utils.repr_hex(s)
Convert provided bitstring to a simple string of hex digits
- scapy.utils.restart()
Restarts scapy
- scapy.utils.sane(x)
- scapy.utils.sane_color(x)
- scapy.utils.save_object(fname, obj)
Pickle a Python object
- scapy.utils.str2mac(s)
- scapy.utils.strand(s1, s2)
Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2 must be of same length.
- scapy.utils.strxor(s1, s2)
Returns the binary XOR of the 2 provided strings s1 and s2. s1 and s2 must be of same length.
- scapy.utils.tcpdump(pktlist=None, dump=False, getfd=False, args=None, flt=None, prog=None, getproc=False, quiet=False, use_tempfile=None, read_stdin_opts=None, linktype=None, wait=True, _suppress=False)
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, args=None, **kwargs)
Run tshark on a list of packets.
- Parameters
args – If not specified, defaults to
tshark -V
.
See
tcpdump()
for more parameters.
- scapy.utils.tex_escape(x)
- scapy.utils.valid_ip(addr)
- scapy.utils.valid_ip6(addr)
- scapy.utils.valid_mac(mac)
- scapy.utils.valid_net(addr)
- scapy.utils.valid_net6(addr)
- scapy.utils.whois(ip_address)
Whois client for Python
- scapy.utils.wireshark(pktlist, wait=False, **kwargs)
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.wrpcap(filename, pkt, *args, **kargs)
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.zerofree_randstring(length)
Returns a random string of length (length >= 0) without zero in it.