def autorun_get_ansi_interactive_session(cmds, **kargs): ct = conf.color_theme try: conf.color_theme = DefaultTheme() s, res = autorun_get_interactive_session(cmds, **kargs) finally: conf.color_theme = ct return s, res
def autorun_get_ansi_interactive_session(cmds, **kargs): # type: (str, **Any) -> Tuple[str, Any] ct = conf.color_theme try: conf.color_theme = DefaultTheme() s, res = autorun_get_interactive_session(cmds, **kargs) finally: conf.color_theme = ct return s, res
def init_session(mydict=None, session_name="", STARTUP_FILE=DEFAULT_STARTUP_FILE): global session scapy_builtins = __import__("all", globals(), locals(), ".").__dict__ for name, sym in scapy_builtins.iteritems(): if name[0] != '_': __builtin__.__dict__[name] = sym globkeys = scapy_builtins.keys() globkeys.append("scapy_session") scapy_builtins = None # XXX replace with "with" statement if mydict is not None: __builtin__.__dict__.update(mydict) globkeys += mydict.keys() conf.color_theme = DefaultTheme() if STARTUP_FILE: _read_config_file(STARTUP_FILE) if session_name: try: os.stat(session_name) except OSError: log_loading.info("New session [%s]" % session_name) else: try: try: session = cPickle.load(gzip.open(session_name, "rb")) except IOError: session = cPickle.load(open(session_name, "rb")) log_loading.info("Using session [%s]" % session_name) except EOFError: log_loading.error("Error opening session [%s]" % session_name) except AttributeError: log_loading.error( "Error opening session [%s]. Attribute missing" % session_name) if session: if "conf" in session: conf.configure(session["conf"]) session["conf"] = conf else: conf.session = session_name session = {"conf": conf} else: session = {"conf": conf} __builtin__.__dict__["scapy_session"] = session return globkeys
def interact(mydict=None, argv=None, mybanner=None, loglevel=20): global SESSION global GLOBKEYS console_handler = logging.StreamHandler() console_handler.setFormatter( logging.Formatter("%(levelname)s: %(message)s")) log_scapy.addHandler(console_handler) from scapy.config import conf conf.color_theme = DefaultTheme() conf.interactive = True if loglevel is not None: conf.logLevel = loglevel STARTUP_FILE = DEFAULT_STARTUP_FILE PRESTART_FILE = DEFAULT_PRESTART_FILE session_name = None if argv is None: argv = sys.argv try: opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d") for opt, parm in opts[0]: if opt == "-h": _usage() elif opt == "-s": session_name = parm elif opt == "-c": STARTUP_FILE = parm elif opt == "-C": STARTUP_FILE = None elif opt == "-p": PRESTART_FILE = parm elif opt == "-P": PRESTART_FILE = None elif opt == "-d": conf.logLevel = max(1, conf.logLevel - 10) if len(opts[1]) > 0: raise getopt.GetoptError("Too many parameters : [%s]" % " ".join(opts[1])) except getopt.GetoptError as msg: log_loading.error(msg) sys.exit(1) init_session(session_name, mydict) if STARTUP_FILE: _read_config_file(STARTUP_FILE, interactive=True) if PRESTART_FILE: _read_config_file(PRESTART_FILE, interactive=True) if not conf.interactive_shell or conf.interactive_shell.lower() in [ "ipython", "auto" ]: try: import IPython from IPython import start_ipython except ImportError: log_loading.warning( "IPython not available. Using standard Python shell " "instead.\nAutoCompletion, History are disabled.") if WINDOWS: log_loading.warning( "IPyton not available. On Windows, colors are disabled") conf.color_theme = BlackAndWhite() IPYTHON = False else: IPYTHON = True else: IPYTHON = False if conf.fancy_prompt: the_logo = [ " ", " aSPY//YASa ", " apyyyyCY//////////YCa ", " sY//////YSpcs scpCY//Pp ", " ayp ayyyyyyySCP//Pp syY//C ", " AYAsAYYYYYYYY///Ps cY//S", " pCCCCY//p cSSps y//Y", " SPPPP///a pP///AC//Y", " A//A cyP////C", " p///Ac sC///a", " P////YCpc A//A", " scccccp///pSP///p p//Y", " sY/////////y caa S//P", " cayCyayP//Ya pY/Ya", " sY/PsY////YCc aC//Yp ", " sc sccaCY//PCypaapyCP//YSs ", " spCPY//////YPSps ", " ccaacs ", " ", ] the_banner = [ "", "", " |", " | Welcome to Scapy", " | Version %s" % conf.version, " |", " | https://github.com/secdev/scapy", " |", " | Have fun!", " |", ] quote, author = choice(QUOTES) the_banner.extend(_prepare_quote(quote, author, max_len=39)) the_banner.append(" |") the_banner = "\n".join( logo + banner for logo, banner in six.moves.zip_longest(( conf.color_theme.logo(line) for line in the_logo), (conf.color_theme.success(line) for line in the_banner), fillvalue="")) else: the_banner = "Welcome to Scapy (%s)" % conf.version if mybanner is not None: the_banner += "\n" the_banner += mybanner if IPYTHON: banner = the_banner + " using IPython %s\n" % IPython.__version__ try: from traitlets.config.loader import Config except ImportError: log_loading.warning( "traitlets not available. Some Scapy shell features won't be " "available.") try: start_ipython(display_banner=False, user_ns=SESSION, exec_lines=["print(\"\"\"" + banner + "\"\"\")"]) except: code.interact(banner=the_banner, local=SESSION) else: cfg = Config() try: get_ipython except NameError: # Set "classic" prompt style when launched from run_scapy(.bat) files # Register and apply scapy color+prompt style apply_ipython_style(shell=cfg.TerminalInteractiveShell) cfg.TerminalInteractiveShell.confirm_exit = False cfg.TerminalInteractiveShell.separate_in = u'' if int(IPython.__version__[0]) >= 6: cfg.TerminalInteractiveShell.term_title_format = "Scapy v" + conf.version else: cfg.TerminalInteractiveShell.term_title = False cfg.HistoryAccessor.hist_file = conf.histfile cfg.InteractiveShell.banner1 = banner # configuration can thus be specified here. try: start_ipython(config=cfg, user_ns=SESSION) except (AttributeError, TypeError): code.interact(banner=the_banner, local=SESSION) else: code.interact(banner=the_banner, local=SESSION) if conf.session: save_session(conf.session, SESSION) for k in GLOBKEYS: try: del (six.moves.builtins.__dict__[k]) except: pass
if PRESTART_FILE: _read_config_file(PRESTART_FILE) scapy_builtins = __import__("all", globals(), locals(), ".").__dict__ for name, sym in scapy_builtins.iteritems(): if name[0] != '_': __builtin__.__dict__[name] = sym globkeys = scapy_builtins.keys() globkeys.append("scapy_session") scapy_builtins = None # XXX replace with "with" statement if mydict is not None: __builtin__.__dict__.update(mydict) globkeys += mydict.keys() conf.color_theme = DefaultTheme() if STARTUP_FILE: _read_config_file(STARTUP_FILE) if session_name: try: os.stat(session_name) except OSError: log_loading.info("New session [%s]" % session_name) else: try: try: session = cPickle.load(gzip.open(session_name, "rb")) except IOError: session = cPickle.load(open(session_name, "rb")) log_loading.info("Using session [%s]" % session_name)
def interact(mydict=None, argv=None, mybanner=None, loglevel=logging.INFO): """Starts Scapy's console.""" global SESSION global GLOBKEYS try: if WINDOWS: # colorama is bundled within IPython. # logging.StreamHandler will be overwritten when called, # We can't wait for IPython to call it import colorama colorama.init() # Success console_handler = logging.StreamHandler() console_handler.setFormatter( ScapyColoredFormatter( "%(levelname)s: %(message)s", ) ) except ImportError: # Failure: ignore colors in the logger console_handler = logging.StreamHandler() console_handler.setFormatter( logging.Formatter( "%(levelname)s: %(message)s", ) ) log_scapy.addHandler(console_handler) # We're in interactive mode, let's throw the DeprecationWarnings warnings.simplefilter("always") from scapy.config import conf conf.interactive = True conf.color_theme = DefaultTheme() if loglevel is not None: conf.logLevel = loglevel STARTUP_FILE = DEFAULT_STARTUP_FILE PRESTART_FILE = DEFAULT_PRESTART_FILE session_name = None if argv is None: argv = sys.argv try: opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d:H") for opt, parm in opts[0]: if opt == "-h": _usage() elif opt == "-H": conf.fancy_prompt = False conf.verb = 30 elif opt == "-s": session_name = parm elif opt == "-c": STARTUP_FILE = parm elif opt == "-C": STARTUP_FILE = None elif opt == "-p": PRESTART_FILE = parm elif opt == "-P": PRESTART_FILE = None elif opt == "-d": conf.logLevel = max(1, conf.logLevel - 10) if len(opts[1]) > 0: raise getopt.GetoptError("Too many parameters : [%s]" % " ".join(opts[1])) # noqa: E501 except getopt.GetoptError as msg: log_loading.error(msg) sys.exit(1) # Reset sys.argv, otherwise IPython thinks it is for him sys.argv = sys.argv[:1] init_session(session_name, mydict) if STARTUP_FILE: _read_config_file(STARTUP_FILE, interactive=True) if PRESTART_FILE: _read_config_file(PRESTART_FILE, interactive=True) if not conf.interactive_shell or conf.interactive_shell.lower() in [ "ipython", "auto" ]: try: import IPython from IPython import start_ipython except ImportError: log_loading.warning( "IPython not available. Using standard Python shell " "instead.\nAutoCompletion, History are disabled." ) if WINDOWS: log_loading.warning( "On Windows, colors are also disabled" ) conf.color_theme = BlackAndWhite() IPYTHON = False else: IPYTHON = True else: IPYTHON = False if conf.fancy_prompt: from scapy.utils import get_terminal_width mini_banner = (get_terminal_width() or 84) <= 75 the_logo = [ " ", " aSPY//YASa ", " apyyyyCY//////////YCa ", " sY//////YSpcs scpCY//Pp ", " ayp ayyyyyyySCP//Pp syY//C ", " AYAsAYYYYYYYY///Ps cY//S", " pCCCCY//p cSSps y//Y", " SPPPP///a pP///AC//Y", " A//A cyP////C", " p///Ac sC///a", " P////YCpc A//A", " scccccp///pSP///p p//Y", " sY/////////y caa S//P", " cayCyayP//Ya pY/Ya", " sY/PsY////YCc aC//Yp ", " sc sccaCY//PCypaapyCP//YSs ", " spCPY//////YPSps ", " ccaacs ", " ", ] # Used on mini screens the_logo_mini = [ " .SYPACCCSASYY ", "P /SCS/CCS ACS", " /A AC", " A/PS /SPPS", " YP (SC", " SPS/A. SC", " Y/PACC PP", " PY*AYC CAA", " YYCY//SCYP ", ] the_banner = [ "", "", " |", " | Welcome to Scapy", " | Version %s" % conf.version, " |", " | https://github.com/secdev/scapy", " |", " | Have fun!", " |", ] if mini_banner: the_logo = the_logo_mini the_banner = [x[2:] for x in the_banner[3:-1]] the_banner = [""] + the_banner + [""] else: quote, author = choice(QUOTES) the_banner.extend(_prepare_quote(quote, author, max_len=39)) the_banner.append(" |") the_banner = "\n".join( logo + banner for logo, banner in six.moves.zip_longest( (conf.color_theme.logo(line) for line in the_logo), (conf.color_theme.success(line) for line in the_banner), fillvalue="" ) ) else: the_banner = "Welcome to Scapy (%s)" % conf.version if mybanner is not None: the_banner += "\n" the_banner += mybanner if IPYTHON: banner = the_banner + " using IPython %s\n" % IPython.__version__ try: from traitlets.config.loader import Config except ImportError: log_loading.warning( "traitlets not available. Some Scapy shell features won't be " "available." ) try: start_ipython( display_banner=False, user_ns=SESSION, exec_lines=["print(\"\"\"" + banner + "\"\"\")"] ) except Exception: code.interact(banner=the_banner, local=SESSION) else: cfg = Config() try: get_ipython except NameError: # Set "classic" prompt style when launched from run_scapy(.bat) files # noqa: E501 # Register and apply scapy color+prompt style apply_ipython_style(shell=cfg.TerminalInteractiveShell) cfg.TerminalInteractiveShell.confirm_exit = False cfg.TerminalInteractiveShell.separate_in = u'' if int(IPython.__version__[0]) >= 6: cfg.TerminalInteractiveShell.term_title_format = "Scapy v%s" % conf.version # noqa: E501 else: cfg.TerminalInteractiveShell.term_title = False cfg.HistoryAccessor.hist_file = conf.histfile cfg.InteractiveShell.banner1 = banner # configuration can thus be specified here. try: start_ipython(config=cfg, user_ns=SESSION) except (AttributeError, TypeError): code.interact(banner=the_banner, local=SESSION) else: code.interact(banner=the_banner, local=SESSION) if conf.session: save_session(conf.session, SESSION) for k in GLOBKEYS: try: del(six.moves.builtins.__dict__[k]) except Exception: pass
def main(): argv = sys.argv[1:] logger = logging.getLogger("scapy") logger.addHandler(logging.StreamHandler()) import scapy print(dash + " UTScapy - Scapy %s - %s" % (scapy.__version__, sys.version.split(" ")[0])) # Parse arguments FORMAT = Format.ANSI OUTPUTFILE = sys.stdout LOCAL = 0 NUM = None NON_ROOT = False KW_OK = [] KW_KO = [] DUMP = 0 DOCS = 0 CRC = True BREAKFAILED = True ONLYFAILED = False VERB = 3 GLOB_PREEXEC = "" PREEXEC_DICT = {} MODULES = [] TESTFILES = [] ANNOTATIONS_MODE = False INTERPRETER = False try: opts = getopt.getopt(argv, "o:t:T:c:f:hbln:m:k:K:DRdCiFqNP:s:x") for opt, optarg in opts[0]: if opt == "-h": usage() elif opt == "-b": BREAKFAILED = False elif opt == "-F": ONLYFAILED = True elif opt == "-q": VERB -= 1 elif opt == "-D": DUMP = 2 elif opt == "-R": DOCS = 1 elif opt == "-d": DUMP = 1 elif opt == "-C": CRC = False elif opt == "-i": INTERPRETER = True elif opt == "-x": ANNOTATIONS_MODE = True elif opt == "-P": GLOB_PREEXEC += "\n" + optarg elif opt == "-f": try: FORMAT = Format.from_string(optarg) except KeyError as msg: raise getopt.GetoptError("Unknown output format %s" % msg) elif opt == "-t": TESTFILES.append(optarg) TESTFILES = resolve_testfiles(TESTFILES) elif opt == "-T": TESTFILES.remove(optarg) elif opt == "-c": data = parse_config_file(optarg, VERB) BREAKFAILED = data.breakfailed ONLYFAILED = data.onlyfailed VERB = data.verb DUMP = data.dump CRC = data.crc PREEXEC_DICT = data.preexec GLOB_PREEXEC = data.global_preexec OUTPUTFILE = data.outfile TESTFILES = data.testfiles LOCAL = 1 if data.local else 0 NUM = data.num MODULES = data.modules KW_OK.extend(data.kw_ok) KW_KO.extend(data.kw_ko) try: FORMAT = Format.from_string(data.format) except KeyError as msg: raise getopt.GetoptError("Unknown output format %s" % msg) TESTFILES = resolve_testfiles(TESTFILES) for testfile in resolve_testfiles(data.remove_testfiles): try: TESTFILES.remove(testfile) except ValueError: error_m = "Cannot remove %s from test files" % testfile raise getopt.GetoptError(error_m) elif opt == "-o": OUTPUTFILE = optarg if not os.access(os.path.dirname(os.path.abspath(OUTPUTFILE)), os.W_OK): raise getopt.GetoptError("Cannot write to file %s" % OUTPUTFILE) elif opt == "-l": LOCAL = 1 elif opt == "-n": NUM = [] for v in (x.strip() for x in optarg.split(",")): try: NUM.append(int(v)) except ValueError: v1, v2 = [int(e) for e in v.split('-', 1)] NUM.extend(range(v1, v2 + 1)) elif opt == "-N": NON_ROOT = True elif opt == "-m": MODULES.append(optarg) elif opt == "-k": KW_OK.extend(optarg.split(",")) elif opt == "-K": KW_KO.extend(optarg.split(",")) except getopt.GetoptError as msg: print("ERROR:", msg) raise SystemExit if FORMAT in [Format.LIVE, Format.ANSI]: theme = DefaultTheme() else: theme = BlackAndWhite() # Disable tests if needed # Discard Python3 tests when using Python2 if six.PY2: KW_KO.append("python3_only") if VERB > 2: print(" " + arrow + " Python 2 mode") try: if NON_ROOT or os.getuid() != 0: # Non root # Discard root tests KW_KO.append("needs_root") if VERB > 2: print(" " + arrow + " Non-root mode") except AttributeError: pass if conf.use_pcap or WINDOWS: KW_KO.append("not_libpcap") if VERB > 2: print(" " + arrow + " libpcap mode") KW_KO.append("disabled") # Process extras if six.PY3: KW_KO.append("FIXME_py3") if ANNOTATIONS_MODE: try: from pyannotate_runtime import collect_types except ImportError: raise ImportError("Please install pyannotate !") collect_types.init_types_collection() collect_types.start() if VERB > 2: print(" " + arrow + " Booting scapy...") try: from scapy import all as scapy except Exception as e: print("[CRITICAL]: Cannot import Scapy: %s" % e) traceback.print_exc() sys.exit(1) # Abort the tests for m in MODULES: try: mod = import_module(m) six.moves.builtins.__dict__.update(mod.__dict__) except ImportError as e: raise getopt.GetoptError("cannot import [%s]: %s" % (m, e)) autorun_func = { Format.TEXT: scapy.autorun_get_text_interactive_session, Format.ANSI: scapy.autorun_get_ansi_interactive_session, Format.HTML: scapy.autorun_get_html_interactive_session, Format.LATEX: scapy.autorun_get_latex_interactive_session, Format.XUNIT: scapy.autorun_get_text_interactive_session, Format.LIVE: scapy.autorun_get_live_interactive_session, } if VERB > 2: print(" " + arrow + " Discovering tests files...") glob_output = "" glob_result = 0 glob_title = None UNIQUE = len(TESTFILES) == 1 # Resolve tags and asterix for prex in six.iterkeys(copy.copy(PREEXEC_DICT)): if "*" in prex: pycode = PREEXEC_DICT[prex] del PREEXEC_DICT[prex] for gl in glob.iglob(prex): _pycode = pycode.replace( "%name%", os.path.splitext(os.path.split(gl)[1])[0]) # noqa: E501 PREEXEC_DICT[gl] = _pycode pos_begin = 0 runned_campaigns = [] from scapy.main import _scapy_builtins scapy_ses = _scapy_builtins() import_UTscapy_tools(scapy_ses) # Execute all files for TESTFILE in TESTFILES: if VERB > 2: print(theme.green(dash + " Loading: %s" % TESTFILE)) PREEXEC = PREEXEC_DICT[ TESTFILE] if TESTFILE in PREEXEC_DICT else GLOB_PREEXEC with open(TESTFILE) as testfile: output, result, campaign = execute_campaign( testfile, OUTPUTFILE, PREEXEC, NUM, KW_OK, KW_KO, DUMP, DOCS, FORMAT, VERB, ONLYFAILED, CRC, INTERPRETER, autorun_func, theme, pos_begin=pos_begin, scapy_ses=copy.copy(scapy_ses)) runned_campaigns.append(campaign) pos_begin = campaign.end_pos if UNIQUE: glob_title = campaign.title glob_output += output if not result: glob_result = 1 if BREAKFAILED: break if VERB > 2: print(checkmark + " All campaigns executed. Writing output...") if ANNOTATIONS_MODE: collect_types.stop() collect_types.dump_stats("pyannotate_results") # Concenate outputs if FORMAT == Format.HTML: glob_output = pack_html_campaigns(runned_campaigns, glob_output, LOCAL, glob_title) if FORMAT == Format.LATEX: glob_output = pack_latex_campaigns(runned_campaigns, glob_output, LOCAL, glob_title) # Write the final output # Note: on Python 2, we force-encode to ignore ascii errors # on Python 3, we need to detect the type of stream if OUTPUTFILE == sys.stdout: print(glob_output, file=OUTPUTFILE) else: with open(OUTPUTFILE, "wb") as f: f.write( glob_output.encode("utf8", "ignore") if 'b' in f.mode or six.PY2 else glob_output) # Print end message if VERB > 2: if glob_result == 0: print(theme.green("UTscapy ended successfully")) else: print(theme.red("UTscapy ended with error code %s" % glob_result)) # Check active threads if VERB > 2: if threading.active_count() > 1: print("\nWARNING: UNFINISHED THREADS") print(threading.enumerate()) import multiprocessing processes = multiprocessing.active_children() if processes: print("\nWARNING: UNFINISHED PROCESSES") print(processes) sys.stdout.flush() # Return state return glob_result
def interact(mydict=None, argv=None, mybanner=None, loglevel=20): global session global globkeys import code, sys, os, getopt, re from scapy.config import conf conf.interactive = True if loglevel is not None: conf.logLevel = loglevel console_handler = logging.StreamHandler() console_handler.setFormatter( logging.Formatter("%(levelname)s: %(message)s")) log_scapy.addHandler(console_handler) the_banner = "Welcome to Scapy (%s)" if mybanner is not None: the_banner += "\n" the_banner += mybanner if argv is None: argv = sys.argv import atexit try: import rlcompleter, readline except ImportError: log_loading.info("Can't load Python libreadline or completer") READLINE = 0 else: READLINE = 1 class ScapyCompleter(rlcompleter.Completer): def global_matches(self, text): matches = [] n = len(text) for lst in [dir(six.moves.builtins), session]: for word in lst: if word[:n] == text and word != "__builtins__": matches.append(word) return matches def attr_matches(self, text): m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return [] expr, attr = m.group(1, 3) try: object = eval(expr) except: try: object = eval(expr, session) except (NameError, AttributeError): return [] from scapy.packet import Packet, Packet_metaclass if isinstance(object, Packet) or isinstance( object, Packet_metaclass): words = [x for x in dir(object) if x[0] != "_"] words += [x.name for x in object.fields_desc] else: words = dir(object) if hasattr(object, "__class__"): words = words + rlcompleter.get_class_members( object.__class__) matches = [] n = len(attr) for word in words: if word[:n] == attr and word != "__builtins__": matches.append("%s.%s" % (expr, word)) return matches readline.set_completer(ScapyCompleter().complete) readline.parse_and_bind("C-o: operate-and-get-next") readline.parse_and_bind("tab: complete") STARTUP_FILE = DEFAULT_STARTUP_FILE PRESTART_FILE = DEFAULT_PRESTART_FILE session_name = None try: opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d") for opt, parm in opts[0]: if opt == "-h": _usage() elif opt == "-s": session_name = parm elif opt == "-c": STARTUP_FILE = parm elif opt == "-C": STARTUP_FILE = None elif opt == "-p": PRESTART_FILE = parm elif opt == "-P": PRESTART_FILE = None elif opt == "-d": conf.logLevel = max(1, conf.logLevel - 10) if len(opts[1]) > 0: raise getopt.GetoptError("Too many parameters : [%s]" % " ".join(opts[1])) except getopt.GetoptError as msg: log_loading.error(msg) sys.exit(1) conf.color_theme = DefaultTheme() if STARTUP_FILE: _read_config_file(STARTUP_FILE) if PRESTART_FILE: _read_config_file(PRESTART_FILE) init_session(session_name, mydict) if READLINE: if conf.histfile: try: readline.read_history_file(conf.histfile) except IOError: pass atexit.register(scapy_write_history_file, readline) atexit.register(scapy_delete_temp_files) IPYTHON = False if conf.interactive_shell.lower() == "ipython": try: import IPython IPYTHON = True except ImportError as e: log_loading.warning( "IPython not available. Using standard Python shell instead.") IPYTHON = False if IPYTHON: banner = the_banner % ( conf.version) + " using IPython %s" % IPython.__version__ # Old way to embed IPython kept for backward compatibility try: args = [''] # IPython command line args (will be seen as sys.argv) ipshell = IPython.Shell.IPShellEmbed(args, banner=banner) ipshell(local_ns=session) except AttributeError as e: pass # In the IPython cookbook, see 'Updating-code-for-use-with-IPython-0.11-and-later' IPython.embed(user_ns=session, banner2=banner) else: code.interact(banner=the_banner % (conf.version), local=session, readfunc=conf.readfunc) if conf.session: save_session(conf.session, session) for k in globkeys: try: del (six.moves.builtins.__dict__[k]) except: pass
def interact(mydict=None, argv=None, mybanner=None, loglevel=20): global SESSION global GLOBKEYS console_handler = logging.StreamHandler() console_handler.setFormatter( logging.Formatter("%(levelname)s: %(message)s")) log_scapy.addHandler(console_handler) from scapy.config import conf conf.color_theme = DefaultTheme() conf.interactive = True if loglevel is not None: conf.logLevel = loglevel STARTUP_FILE = DEFAULT_STARTUP_FILE PRESTART_FILE = DEFAULT_PRESTART_FILE session_name = None if argv is None: argv = sys.argv try: opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d") for opt, parm in opts[0]: if opt == "-h": _usage() elif opt == "-s": session_name = parm elif opt == "-c": STARTUP_FILE = parm elif opt == "-C": STARTUP_FILE = None elif opt == "-p": PRESTART_FILE = parm elif opt == "-P": PRESTART_FILE = None elif opt == "-d": conf.logLevel = max(1, conf.logLevel - 10) if len(opts[1]) > 0: raise getopt.GetoptError("Too many parameters : [%s]" % " ".join(opts[1])) except getopt.GetoptError as msg: log_loading.error(msg) sys.exit(1) if STARTUP_FILE: _read_config_file(STARTUP_FILE, interactive=True) if PRESTART_FILE: _read_config_file(PRESTART_FILE, interactive=True) init_session(session_name, mydict) if conf.fancy_prompt: the_logo = [ " ", " aSPY//YASa ", " apyyyyCY//////////YCa ", " sY//////YSpcs scpCY//Pp ", " ayp ayyyyyyySCP//Pp syY//C ", " AYAsAYYYYYYYY///Ps cY//S", " pCCCCY//p cSSps y//Y", " SPPPP///a pP///AC//Y", " A//A cyP////C", " p///Ac sC///a", " P////YCpc A//A", " scccccp///pSP///p p//Y", " sY/////////y caa S//P", " cayCyayP//Ya pY/Ya", " sY/PsY////YCc aC//Yp ", " sc sccaCY//PCypaapyCP//YSs ", " spCPY//////YPSps ", " ccaacs ", " ", ] the_banner = [ "", "", " |", " | Welcome to Scapy", " | Version %s" % conf.version, " |", " | https://github.com/secdev/scapy", " |", " | Have fun!", " |", ] quote, author = choice(QUOTES) the_banner.extend(_prepare_quote(quote, author, max_len=39)) the_banner.append(" |") the_banner = "\n".join( logo + banner for logo, banner in six.moves.zip_longest(( conf.color_theme.logo(line) for line in the_logo), (conf.color_theme.success(line) for line in the_banner), fillvalue="")) else: the_banner = "Welcome to Scapy (%s)" % conf.version if mybanner is not None: the_banner += "\n" the_banner += mybanner IPYTHON = False if not conf.interactive_shell or conf.interactive_shell.lower() in [ "ipython", "auto" ]: try: IPython IPYTHON = True except NameError as e: log_loading.warning( "IPython not available. Using standard Python shell instead. " "AutoCompletion, History are disabled.") IPYTHON = False init_session(session_name, mydict) if IPYTHON: banner = the_banner + " using IPython %s\n" % IPython.__version__ from IPython.terminal.embed import InteractiveShellEmbed from IPython.terminal.prompts import Prompts, Token from IPython.utils.generics import complete_object from traitlets.config.loader import Config from scapy.packet import Packet cfg = Config() @complete_object.when_type(Packet) def complete_packet(obj, prev_completions): return prev_completions + [fld.name for fld in obj.fields_desc] try: get_ipython except NameError: # Set "classic" prompt style when launched from run_scapy(.bat) files class ClassicPrompt(Prompts): def in_prompt_tokens(self, cli=None): return [ (Token.Prompt, '>>> '), ] def out_prompt_tokens(self): return [ (Token.OutPrompt, ''), ] cfg.TerminalInteractiveShell.prompts_class = ClassicPrompt # Set classic prompt style apply_ipython_color(shell=cfg.TerminalInteractiveShell ) # Register and apply scapy color style cfg.TerminalInteractiveShell.confirm_exit = False # Remove confirm exit cfg.TerminalInteractiveShell.separate_in = u'' # Remove spacing line cfg.TerminalInteractiveShell.hist_file = conf.histfile # configuration can thus be specified here. ipshell = InteractiveShellEmbed( config=cfg, banner1=banner, hist_file=conf.histfile if conf.histfile else None, user_ns=SESSION) ipshell(local_ns=SESSION) else: code.interact(banner=the_banner, local=SESSION) if conf.session: save_session(conf.session, SESSION) for k in GLOBKEYS: try: del (six.moves.builtins.__dict__[k]) except: pass
from pprint import pprint import scapy.modules.gnuradio as gnuradio import snout.util as util import yaml from prettytable import PrettyTable from scapy.config import conf as scapy_config from scapy.themes import DefaultTheme from snout import Snout from snout.core.radio import Radio, ScanSelector, TransmitSelector from snout.core.config import Config as cfg from snout.util.iot_click import (ProtocolArg, ChannelsOption, PythonLiteralOption, iot_click, pos_callback, form_cli) scapy_config.color_theme = DefaultTheme() scapy_config.dot15d4_protocol = 'zigbee' # set to zigbee instead of sixlowpan process = None # update gnuradio custom modulations gnuradio.update_custom_modulation(protocol='Btle', hardware='hackrf', mode='rx', mode_path='btle_rx') # Click command line args ###################################################### CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"], max_content_width=110)