def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, replay_args=None, # noqa: E501 parse_results=False): """Send packets at layer 2 using tcpreplay for performance :param pps: packets per second :param mpbs: MBits per second :param realtime: use packet's timestamp, bending time with real-time value :param loop: number of times to process the packet list :param file_cache: cache packets in RAM instead of reading from disk at each iteration :param iface: output interface :param replay_args: List of additional tcpreplay args (List[str]) :param parse_results: Return a dictionary of information outputted by tcpreplay (default=False) :returns: stdout, stderr, command used """ if iface is None: iface = conf.iface argv = [conf.prog.tcpreplay, "--intf1=%s" % network_name(iface)] if pps is not None: argv.append("--pps=%i" % pps) elif mbps is not None: argv.append("--mbps=%f" % mbps) elif realtime is not None: argv.append("--multiplier=%f" % realtime) else: argv.append("--topspeed") if loop: argv.append("--loop=%i" % loop) if file_cache: argv.append("--preload-pcap") # Check for any additional args we didn't cover. if replay_args is not None: argv.extend(replay_args) f = get_temp_file() argv.append(f) wrpcap(f, x) results = None with ContextManagerSubprocess(conf.prog.tcpreplay): try: cmd = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except KeyboardInterrupt: log_interactive.info("Interrupted by user") except Exception: os.unlink(f) raise else: stdout, stderr = cmd.communicate() if stderr: log_runtime.warning(stderr.decode()) if parse_results: results = _parse_tcpreplay_result(stdout, stderr, argv) elif conf.verb > 2: log_runtime.info(stdout.decode()) os.unlink(f) return results
def svgdump(self, filename=None, **kargs): # type: (Optional[str], **Any) -> None """ svgdump(filename=None, layer_shift=0, rebuild=1) Creates an SVG file describing a packet. If filename is not provided a temporary file is created and gs is called. :param filename: the file's filename """ from scapy.config import conf from scapy.utils import get_temp_file, ContextManagerSubprocess canvas = self.canvas_dump(**kargs) if filename is None: fname = cast(str, get_temp_file(autoext=kargs.get("suffix", ".svg"))) canvas.writeSVGfile(fname) if WINDOWS and conf.prog.svgreader is None: os.startfile(fname) else: with ContextManagerSubprocess(conf.prog.svgreader): subprocess.Popen([conf.prog.svgreader, fname]) else: canvas.writeSVGfile(filename) print()
def http_request(host, path="/", port=80, timeout=3, display=False, verbose=0, iptables=False, **headers): """Util to perform an HTTP request, using the TCP_client. :param host: the host to connect to :param path: the path of the request (default /) :param port: the port (default 80) :param timeout: timeout before None is returned :param display: display the resullt in the default browser (default False) :param iptables: temporarily prevents the kernel from answering with a TCP RESET message. :param headers: any additional headers passed to the request :returns: the HTTPResponse packet """ http_headers = { "Accept_Encoding": b'gzip, deflate', "Cache_Control": b'no-cache', "Pragma": b'no-cache', "Connection": b'keep-alive', "Host": host, "Path": path, } http_headers.update(headers) req = HTTP() / HTTPRequest(**http_headers) tcp_client = TCP_client.tcplink(HTTP, host, port, debug=verbose) ans = None if iptables: ip = tcp_client.atmt.dst iptables_rule = "iptables -%c INPUT -s %s -p tcp --sport 80 -j DROP" assert (os.system(iptables_rule % ('A', ip)) == 0) try: ans = tcp_client.sr1(req, timeout=timeout, verbose=verbose) finally: tcp_client.close() if iptables: assert (os.system(iptables_rule % ('D', ip)) == 0) if ans: if display: if Raw not in ans: warning("No HTTP content returned. Cannot display") return ans # Write file file = get_temp_file(autoext=".html") with open(file, "wb") as fd: fd.write(ans.load) # Open browser if WINDOWS: os.startfile(file) else: with ContextManagerSubprocess(conf.prog.universal_open): subprocess.Popen([conf.prog.universal_open, file]) return ans
def http_request(host, path="/", port=80, timeout=3, display=False, verbose=None, **headers): """Util to perform an HTTP request, using the TCP_client. :param host: the host to connect to :param path: the path of the request (default /) :param port: the port (default 80) :param timeout: timeout before None is returned :param display: display the resullt in the default browser (default False) :param headers: any additional headers passed to the request :returns: the HTTPResponse packet """ http_headers = { "Accept_Encoding": b'gzip, deflate', "Cache_Control": b'no-cache', "Pragma": b'no-cache', "Connection": b'keep-alive', "Host": host, "Path": path, } http_headers.update(headers) req = HTTP() / HTTPRequest(**http_headers) tcp_client = TCP_client.tcplink(HTTP, host, 80) ans = None try: ans = tcp_client.sr1(req, timeout=timeout, verbose=verbose) finally: tcp_client.close() if ans: if display: # Write file file = get_temp_file(autoext=".html") with open(file, "wb") as fd: fd.write(ans.load) # Open browser if WINDOWS: os.startfile(file) else: with ContextManagerSubprocess("http_request()", conf.prog.universal_open): subprocess.Popen([conf.prog.universal_open, file]) else: return ans
def psdump(self, filename=None, **kargs): """Creates a multi-page postcript file with a psdump of every packet filename: name of the file to write to. If empty, a temporary file is used and # noqa: E501 conf.prog.psreader is called""" d = self._dump_document(**kargs) if filename is None: filename = get_temp_file(autoext=".ps") d.writePSfile(filename) if WINDOWS and conf.prog.psreader is None: os.startfile(filename) else: with ContextManagerSubprocess("psdump()", conf.prog.psreader): subprocess.Popen([conf.prog.psreader, filename]) else: d.writePSfile(filename) print()
def start(self): # Wireshark must be running first, because PcapWriter will block until # data has been read! with ContextManagerSubprocess(conf.prog.wireshark): args = [conf.prog.wireshark, "-Slki", "-"] if self.args: args.extend(self.args) proc = subprocess.Popen( args, stdin=subprocess.PIPE, stdout=None, stderr=None, ) self.fname = proc.stdin WrpcapSink.start(self)
def pdfdump(self, filename=None, **kargs): """ pdfdump(filename=None, layer_shift=0, rebuild=1) Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called. :param filename: the file's filename """ from scapy.config import conf from scapy.utils import get_temp_file, ContextManagerSubprocess canvas = self.canvas_dump(**kargs) if filename is None: fname = get_temp_file(autoext=kargs.get("suffix", ".pdf")) canvas.writePDFfile(fname) if WINDOWS and conf.prog.pdfreader is None: os.startfile(fname) else: with ContextManagerSubprocess(conf.prog.pdfreader): subprocess.Popen([conf.prog.pdfreader, fname]) else: canvas.writePDFfile(filename) print()
def http_request(host, path="/", port=80, timeout=3, display=False, verbose=0, raw=False, iptables=False, iface=None, **headers): """Util to perform an HTTP request, using the TCP_client. :param host: the host to connect to :param path: the path of the request (default /) :param port: the port (default 80) :param timeout: timeout before None is returned :param display: display the resullt in the default browser (default False) :param raw: opens a raw socket instead of going through the OS's TCP socket. Scapy will then use its own TCP client. Careful, the OS might cancel the TCP connection with RST. :param iptables: when raw is enabled, this calls iptables to temporarily prevent the OS from sending TCP RST to the host IP. On Linux, you'll almost certainly need this. :param iface: interface to use. Changing this turns on "raw" :param headers: any additional headers passed to the request :returns: the HTTPResponse packet """ from scapy.sessions import TCPSession http_headers = { "Accept_Encoding": b'gzip, deflate', "Cache_Control": b'no-cache', "Pragma": b'no-cache', "Connection": b'keep-alive', "Host": host, "Path": path, } http_headers.update(headers) req = HTTP() / HTTPRequest(**http_headers) ans = None # Open a socket if iface is not None: raw = True if raw: # Use TCP_client on a raw socket iptables_rule = "iptables -%c INPUT -s %s -p tcp --sport 80 -j DROP" if iptables: host = str(Net(host)) assert (os.system(iptables_rule % ('A', host)) == 0) sock = TCP_client.tcplink(HTTP, host, port, debug=verbose, iface=iface) else: # Use a native TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock = StreamSocket(sock, HTTP) # Send the request and wait for the answer try: ans = sock.sr1(req, session=TCPSession(app=True), timeout=timeout, verbose=verbose) finally: sock.close() if raw and iptables: host = str(Net(host)) assert (os.system(iptables_rule % ('D', host)) == 0) if ans: if display: if Raw not in ans: warning("No HTTP content returned. Cannot display") return ans # Write file file = get_temp_file(autoext=".html") with open(file, "wb") as fd: fd.write(ans.load) # Open browser if WINDOWS: os.startfile(file) else: with ContextManagerSubprocess(conf.prog.universal_open): subprocess.Popen([conf.prog.universal_open, file]) return ans