scapy.utils
General utility functions.
- class scapy.utils.ContextManagerCaptureOutput[源代码]
基类:
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)[源代码]
基类:
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)[源代码]
基类:
Decimal
Extended Decimal
This implements arithmetic and comparison with float for backward compatibility
- class scapy.utils.ERFEthernetReader(filename: IO[bytes] | str)[源代码]
基类:
PcapReader
- class scapy.utils.ERFEthernetWriter(filename: IO[bytes] | str, gz: bool = False, append: bool = False, sync: bool = False)[源代码]
基类:
PcapWriter
A stream ERF Ethernet writer with more control than wrerf()
- write(pkt: _PacketIterable) None [源代码]
Writes a Packet, a SndRcvList object, or bytes to a ERF file.
- 参数:
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)[源代码]
基类:
type
- element_class[源代码]
EnumElement
的别名
- class scapy.utils.GenericPcapWriter[源代码]
基类:
object
- linktype: int | None = None
- nano = False
- write_packet(packet: bytes | Packet, sec: float | None = None, usec: int | None = None, caplen: int | None = None, wirelen: int | None = None) None [源代码]
Writes a single packet to the pcap file.
- 参数:
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
.
- 返回:
None
- 返回类型:
None
- class scapy.utils.GenericRawPcapWriter[源代码]
-
- f: IO[bytes] | GzipFile = None
- header_present = False
- nano = False
- sync = False
- write(pkt: _PacketIterable | bytes) None [源代码]
Writes a Packet, a SndRcvList object, or bytes to a pcap file.
- 参数:
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)[源代码]
基类:
RawPcapNgReader
,PcapReader
- alternative[源代码]
PcapReader
的别名
- class scapy.utils.PcapNgWriter(filename: str)[源代码]
-
A stream pcapng writer with more control than wrpcapng()
- class scapy.utils.PcapReader(filename: IO[bytes] | str)[源代码]
-
- alternative[源代码]
PcapNgReader
的别名
- read_all(count: int = -1) PacketList [源代码]
- class scapy.utils.PcapReader_metaclass(name: Any, bases: str, dct: Any)[源代码]
基类:
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)[源代码]
-
A stream PCAP writer with more control than wrpcap()
- class scapy.utils.PeriodicSenderThread(sock: Any, pkt: _PacketIterable, interval: float = 0.5)[源代码]
基类:
Thread
- class scapy.utils.RawPcapNgReader(filename: IO[bytes] | str)[源代码]
-
A stateful pcapng reader. Each packet is returned as bytes.
- alternative[源代码]
RawPcapReader
的别名
- class scapy.utils.RawPcapNgWriter(filename: str)[源代码]
-
A stream pcapng writer with more control than wrpcapng()
- class scapy.utils.RawPcapReader(filename: IO[bytes] | str)[源代码]
基类:
object
A stateful pcap reader. Each packet is returned as a string
- class PacketMetadata(sec, usec, wirelen, caplen)[源代码]
基类:
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[源代码]
RawPcapNgReader
的别名
- dispatch(callback: Callable[[Tuple[bytes, PacketMetadata]], Any]) None [源代码]
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] [源代码]
- 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)[源代码]
-
A stream PCAP writer with more control than wrpcap()
- scapy.utils.chexdump(p: Packet | AnyStr, dump: bool = False) str | None [源代码]
Build a per byte hexadecimal representation
示例
>>> chexdump(IP()) 0x45, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x7c, 0xe7, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01 # noqa: E501
- 参数:
p -- a Packet
dump -- print the view if False
- 返回:
a String only if dump=True
- scapy.utils.colgen(*lstcol: Any, **kargs: Any) Iterator[Any] [源代码]
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 [源代码]
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 [源代码]
Corrupt a given percentage (at least one byte) or number of bytes from a string
- scapy.utils.decode_locale_str(x: bytes) str [源代码]
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 [源代码]
Processes graph description using an external software. This method is used to convert a graphviz format to an image.
- 参数:
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 [源代码]
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 [源代码]
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 [源代码]
Creates a temporary file, and returns its name.
- 参数:
keep -- If False (default), the directory will be recursively deleted when Scapy exits.
- 返回:
A full path to a temporary directory.
- scapy.utils.get_temp_file(keep, autoext, fd)[源代码]
- scapy.utils.get_temp_file(keep=False, autoext='', fd=False)
Creates a temporary file.
- 参数:
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 [源代码]
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, autojunk: bool = False) None [源代码]
Show differences between 2 binary strings, Packets...
For the autojunk parameter, see https://docs.python.org/3.8/library/difflib.html#difflib.SequenceMatcher
- 参数:
a --
b -- The binary strings, packets... to compare
autojunk -- Setting it to True will likely increase the comparison speed a lot on big byte strings, but will reduce accuracy (will tend to miss insertion and see replacements instead for instance).
- scapy.utils.hexdump(p: Packet | AnyStr, dump: bool = False) str | None [源代码]
Build a tcpdump like hexadecimal view
- 参数:
p -- a Packet
dump -- define if the result must be printed or returned in a variable
- 返回:
a String only when dump=True
- scapy.utils.hexedit(pktlist: _PacketIterable) PacketList [源代码]
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 [源代码]
Build a fancy tcpdump like hex from bytes.
- scapy.utils.import_hexcap(input_string: str | None = None) bytes [源代码]
Imports a tcpdump like hexadecimal view
e.g: exported via hexdump() or tcpdump or wireshark's "export as hex"
- 参数:
input_string -- String containing the hexdump input to parse. If None, read from standard input.
- 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.linehexdump(p: Packet | AnyStr, onlyasc: int = 0, onlyhex: int = 0, dump: bool = False) str | None [源代码]
Build an equivalent view of hexdump() on a single line
Note that setting both onlyasc and onlyhex to 1 results in a empty output
- 参数:
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
- 返回:
a String only when dump=True
- scapy.utils.pretty_list(rtlst: List[Tuple[str | List[str], ...]], header: List[Tuple[str, ...]], sortBy: int = 0, borders: bool = False) str [源代码]
Pretty list to fit the terminal, and add header.
- 参数:
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 [源代码]
Read a ERF file and return a packet list
- 参数:
count -- read only <count> packets
- scapy.utils.rdpcap(filename: IO[bytes] | str, count: int = -1) PacketList [源代码]
Read a pcap or pcapng file and return a packet list
- 参数:
count -- read only <count> packets
- scapy.utils.repr_hex(s: bytes) str [源代码]
Convert provided bitstring to a simple string of hex digits
- scapy.utils.strand(s1: bytes, s2: bytes) bytes [源代码]
Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2 must be of same length.
- scapy.utils.strxor(s1: bytes, s2: bytes) bytes [源代码]
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 [源代码]
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.- 参数:
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 [源代码]
Run tshark on a list of packets.
- 参数:
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 [源代码]
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 [源代码]
Write a list of packets to a ERF file
- 参数:
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 [源代码]
Write a list of packets to a pcap file
- 参数:
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 [源代码]
Write a list of packets to a pcapng file
- 参数:
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