Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/scapy/main.py: 17%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

418 statements  

1# SPDX-License-Identifier: GPL-2.0-only 

2# This file is part of Scapy 

3# See https://scapy.net/ for more information 

4# Copyright (C) Philippe Biondi <phil@secdev.org> 

5 

6""" 

7Main module for interactive startup. 

8""" 

9 

10 

11import builtins 

12import code 

13import getopt 

14import glob 

15import importlib 

16import io 

17import logging 

18import os 

19import pathlib 

20import shutil 

21import sys 

22import warnings 

23 

24from itertools import zip_longest 

25from random import choice 

26 

27# Never add any global import, in main.py, that would trigger a 

28# warning message before the console handlers gets added in interact() 

29from scapy.error import ( 

30 log_interactive, 

31 log_loading, 

32 Scapy_Exception, 

33) 

34from scapy.themes import DefaultTheme, BlackAndWhite, apply_ipython_style 

35from scapy.consts import WINDOWS 

36 

37from typing import ( 

38 Any, 

39 Dict, 

40 List, 

41 Literal, 

42 Optional, 

43 Union, 

44 overload, 

45) 

46 

47LAYER_ALIASES = { 

48 "tls": "tls.all", 

49 "msrpce": "msrpce.all", 

50} 

51 

52QUOTES = [ 

53 ("Craft packets like it is your last day on earth.", "Lao-Tze"), 

54 ("Craft packets like I craft my beer.", "Jean De Clerck"), 

55 ("Craft packets before they craft you.", "Socrate"), 

56 ("Craft me if you can.", "IPv6 layer"), 

57 ("To craft a packet, you have to be a packet, and learn how to swim in " 

58 "the wires and in the waves.", "Jean-Claude Van Damme"), 

59 ("We are in France, we say Skappee. OK? Merci.", "Sebastien Chabal"), 

60 ("Wanna support scapy? Star us on GitHub!", "Satoshi Nakamoto"), 

61 ("I'll be back.", "Python 2"), 

62] 

63 

64 

65def _probe_xdg_folder(var, default, *cf): 

66 # type: (str, str, *str) -> Optional[pathlib.Path] 

67 path = pathlib.Path(os.environ.get(var, default)) 

68 try: 

69 if not path.exists(): 

70 # ~ folder doesn't exist. Create according to spec 

71 # https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html 

72 # "If, when attempting to write a file, the destination directory is 

73 # non-existent an attempt should be made to create it with permission 0700." 

74 if WINDOWS: 

75 # https://github.com/secdev/scapy/issues/5190 

76 # 0o700 on Windows is very specific and isn't what we expect. 

77 path.mkdir(exist_ok=True) 

78 else: 

79 path.mkdir(mode=0o700, exist_ok=True) 

80 except Exception: 

81 # There is a gazillion ways this can fail. Most notably, a read-only fs or no 

82 # permissions to even check for folder to exist (e.x. privileges were dropped 

83 # before scapy was started). 

84 return None 

85 return path.joinpath(*cf).resolve() 

86 

87 

88def _probe_config_folder(*cf): 

89 # type: (str) -> Optional[pathlib.Path] 

90 return _probe_xdg_folder( 

91 "XDG_CONFIG_HOME", 

92 os.path.join(os.path.expanduser("~"), ".config"), 

93 *cf 

94 ) 

95 

96 

97def _probe_cache_folder(*cf): 

98 # type: (str) -> Optional[pathlib.Path] 

99 return _probe_xdg_folder( 

100 "XDG_CACHE_HOME", 

101 os.path.join(os.path.expanduser("~"), ".cache"), 

102 *cf 

103 ) 

104 

105 

106def _probe_share_folder(*cf): 

107 # type: (str) -> Optional[pathlib.Path] 

108 return _probe_xdg_folder( 

109 "XDG_DATA_HOME", 

110 os.path.join(os.path.expanduser("~"), ".local", "share"), 

111 *cf 

112 ) 

113 

114 

115def _check_perms(file: Union[pathlib.Path, str]) -> None: 

116 """ 

117 Checks that the permissions of a file are properly user-specific, if sudo is used. 

118 """ 

119 if ( 

120 not WINDOWS and 

121 "SUDO_UID" in os.environ and 

122 "SUDO_GID" in os.environ 

123 ): 

124 # Was started with sudo. Still, chown to the user. 

125 try: 

126 os.chown( 

127 file, 

128 int(os.environ["SUDO_UID"]), 

129 int(os.environ["SUDO_GID"]), 

130 ) 

131 except Exception: 

132 pass 

133 

134 

135def _read_config_file(cf, _globals=globals(), _locals=locals(), 

136 interactive=True, default=None): 

137 # type: (str, Dict[str, Any], Dict[str, Any], bool, Optional[str]) -> None 

138 """Read a config file: execute a python file while loading scapy, that 

139 may contain some pre-configured values. 

140 

141 If _globals or _locals are specified, they will be updated with 

142 the loaded vars. This allows an external program to use the 

143 function. Otherwise, vars are only available from inside the scapy 

144 console. 

145 

146 Parameters: 

147 

148 :param _globals: the globals() vars 

149 :param _locals: the locals() vars 

150 :param interactive: specified whether or not errors should be printed 

151 using the scapy console or raised. 

152 :param default: if provided, set a default value for the config file 

153 

154 ex, content of a config.py file: 

155 'conf.verb = 42\n' 

156 Manual loading: 

157 >>> _read_config_file("./config.py")) 

158 >>> conf.verb 

159 2 

160 

161 """ 

162 cf_path = pathlib.Path(cf) 

163 if not cf_path.exists(): 

164 log_loading.debug("Config file [%s] does not exist.", cf) 

165 if default is None: 

166 return 

167 # We have a default ! set it 

168 try: 

169 if not cf_path.parent.exists(): 

170 cf_path.parent.mkdir(parents=True, exist_ok=True) 

171 _check_perms(cf_path.parent) 

172 

173 with cf_path.open("w") as fd: 

174 fd.write(default) 

175 

176 _check_perms(cf_path) 

177 log_loading.debug("Config file [%s] created with default.", cf) 

178 except OSError: 

179 log_loading.warning("Config file [%s] could not be created.", cf, 

180 exc_info=True) 

181 return 

182 log_loading.debug("Loading config file [%s]", cf) 

183 try: 

184 with open(cf) as cfgf: 

185 exec( 

186 compile(cfgf.read(), cf, 'exec'), 

187 _globals, _locals 

188 ) 

189 except IOError as e: 

190 if interactive: 

191 raise 

192 log_loading.warning("Cannot read config file [%s] [%s]", cf, e) 

193 except Exception: 

194 if interactive: 

195 raise 

196 log_loading.exception("Error during evaluation of config file [%s]", 

197 cf) 

198 

199 

200def _validate_local(k): 

201 # type: (str) -> bool 

202 """Returns whether or not a variable should be imported.""" 

203 return k[0] != "_" and k not in ["range", "map"] 

204 

205 

206# This is ~/.config/scapy 

207SCAPY_CONFIG_FOLDER = _probe_config_folder("scapy") 

208SCAPY_CACHE_FOLDER = _probe_cache_folder("scapy") 

209 

210if SCAPY_CONFIG_FOLDER: 

211 DEFAULT_PRESTART_FILE: Optional[str] = str(SCAPY_CONFIG_FOLDER / "prestart.py") 

212 DEFAULT_STARTUP_FILE: Optional[str] = str(SCAPY_CONFIG_FOLDER / "startup.py") 

213else: 

214 DEFAULT_PRESTART_FILE = None 

215 DEFAULT_STARTUP_FILE = None 

216 

217if "/bash" in os.environ.get("SHELL", ""): 

218 # https://github.com/scop/bash-completion/blob/main/README.md#faq 

219 if "BASH_COMPLETION_USER_DIR" in os.environ: 

220 BASH_COMPLETION_USER_DIR: Optional[pathlib.Path] = pathlib.Path( 

221 os.environ["BASH_COMPLETION_USER_DIR"] 

222 ) 

223 else: 

224 BASH_COMPLETION_USER_DIR = _probe_share_folder("bash-completion") 

225 

226 if BASH_COMPLETION_USER_DIR: 

227 BASH_COMPLETION_FOLDER: Optional[pathlib.Path] = ( 

228 BASH_COMPLETION_USER_DIR / "completions" 

229 ) 

230 else: 

231 BASH_COMPLETION_FOLDER = None 

232else: 

233 BASH_COMPLETION_FOLDER = None 

234 

235 

236# Default scapy prestart.py config file 

237 

238DEFAULT_PRESTART = """ 

239# Scapy CLI 'pre-start' config file 

240# see https://scapy.readthedocs.io/en/latest/api/scapy.config.html#scapy.config.Conf 

241# for all available options 

242 

243# default interpreter 

244conf.interactive_shell = "auto" 

245 

246# color theme (DefaultTheme, BrightTheme, ColorOnBlackTheme, BlackAndWhite, ...) 

247conf.color_theme = DefaultTheme() 

248 

249# disable INFO: tags related to dependencies missing 

250# log_loading.setLevel(logging.WARNING) 

251 

252# extensions to load by default 

253conf.load_extensions = [ 

254 # "scapy-red", 

255 # "scapy-rpc", 

256] 

257 

258# force-use libpcap 

259# conf.use_pcap = True 

260""".strip() 

261 

262 

263def _usage(): 

264 # type: () -> None 

265 print( 

266 "Usage: scapy.py [-c new_startup_file] " 

267 "[-p new_prestart_file] [-C] [-P] [-H]\n" 

268 "Args:\n" 

269 "\t-H: header-less start\n" 

270 "\t-C: do not read startup file\n" 

271 "\t-P: do not read pre-startup file\n" 

272 ) 

273 sys.exit(0) 

274 

275 

276def _add_bash_autocompletion(fname: str, script: pathlib.Path) -> None: 

277 """ 

278 Util function used most notably in setup.py to add a bash autocompletion script. 

279 """ 

280 if BASH_COMPLETION_FOLDER is None: 

281 return 

282 try: 

283 # If already defined, exit. 

284 dest = BASH_COMPLETION_FOLDER / fname 

285 if dest.exists(): 

286 return 

287 

288 # Check that bash autocompletion folder exists 

289 if not BASH_COMPLETION_FOLDER.exists(): 

290 BASH_COMPLETION_FOLDER.mkdir(parents=True, exist_ok=True) 

291 _check_perms(BASH_COMPLETION_FOLDER) 

292 

293 # Copy file 

294 shutil.copy(script, BASH_COMPLETION_FOLDER) 

295 except OSError: 

296 log_loading.warning("Bash autocompletion script could not be copied.", 

297 exc_info=True) 

298 

299 

300###################### 

301# Extension system # 

302###################### 

303 

304 

305def _load(module, globals_dict=None, symb_list=None): 

306 # type: (str, Optional[Dict[str, Any]], Optional[List[str]]) -> None 

307 """Loads a Python module to make variables, objects and functions 

308available globally. 

309 

310 The idea is to load the module using importlib, then copy the 

311symbols to the global symbol table. 

312 

313 """ 

314 if globals_dict is None: 

315 globals_dict = builtins.__dict__ 

316 try: 

317 mod = importlib.import_module(module) 

318 if '__all__' in mod.__dict__: 

319 # import listed symbols 

320 for name in mod.__dict__['__all__']: 

321 if symb_list is not None: 

322 symb_list.append(name) 

323 globals_dict[name] = mod.__dict__[name] 

324 else: 

325 # only import non-private symbols 

326 for name, sym in mod.__dict__.items(): 

327 if _validate_local(name): 

328 if symb_list is not None: 

329 symb_list.append(name) 

330 globals_dict[name] = sym 

331 except Exception: 

332 log_interactive.error("Loading module %s", module, exc_info=True) 

333 

334 

335def load_module(name, globals_dict=None, symb_list=None): 

336 # type: (str, Optional[Dict[str, Any]], Optional[List[str]]) -> None 

337 """Loads a Scapy module to make variables, objects and functions 

338 available globally. 

339 

340 """ 

341 _load("scapy.modules." + name, 

342 globals_dict=globals_dict, symb_list=symb_list) 

343 

344 

345def load_layer(name, globals_dict=None, symb_list=None): 

346 # type: (str, Optional[Dict[str, Any]], Optional[List[str]]) -> None 

347 """Loads a Scapy layer module to make variables, objects and functions 

348 available globally. 

349 

350 """ 

351 _load("scapy.layers." + LAYER_ALIASES.get(name, name), 

352 globals_dict=globals_dict, symb_list=symb_list) 

353 

354 

355def load_contrib(name, globals_dict=None, symb_list=None): 

356 # type: (str, Optional[Dict[str, Any]], Optional[List[str]]) -> None 

357 """Loads a Scapy contrib module to make variables, objects and 

358 functions available globally. 

359 

360 If no contrib module can be found with the given name, try to find 

361 a layer module, since a contrib module may become a layer module. 

362 

363 """ 

364 try: 

365 importlib.import_module("scapy.contrib." + name) 

366 _load("scapy.contrib." + name, 

367 globals_dict=globals_dict, symb_list=symb_list) 

368 except ImportError as e: 

369 # if layer not found in contrib, try in layers 

370 try: 

371 load_layer(name, 

372 globals_dict=globals_dict, symb_list=symb_list) 

373 except ImportError: 

374 raise e # Let's raise the original error to avoid confusion 

375 

376 

377def list_contrib(name=None, # type: Optional[str] 

378 ret=False, # type: bool 

379 _debug=False # type: bool 

380 ): 

381 # type: (...) -> Optional[List[Dict[str, str]]] 

382 """Show the list of all existing contribs. 

383 

384 :param name: filter to search the contribs 

385 :param ret: whether the function should return a dict instead of 

386 printing it 

387 :returns: None or a dictionary containing the results if ret=True 

388 """ 

389 # _debug: checks that all contrib modules have correctly defined: 

390 # # scapy.contrib.description = [...] 

391 # # scapy.contrib.status = [...] 

392 # # scapy.contrib.name = [...] (optional) 

393 # or set the flag: 

394 # # scapy.contrib.description = skip 

395 # to skip the file 

396 if name is None: 

397 name = "*.py" 

398 elif "*" not in name and "?" not in name and not name.endswith(".py"): 

399 name += ".py" 

400 results = [] # type: List[Dict[str, str]] 

401 dir_path = os.path.join(os.path.dirname(__file__), "contrib") 

402 if sys.version_info >= (3, 5): 

403 name = os.path.join(dir_path, "**", name) 

404 iterator = glob.iglob(name, recursive=True) 

405 else: 

406 name = os.path.join(dir_path, name) 

407 iterator = glob.iglob(name) 

408 for f in iterator: 

409 mod = f.replace(os.path.sep, ".").partition("contrib.")[2] 

410 if mod.startswith("__"): 

411 continue 

412 if mod.endswith(".py"): 

413 mod = mod[:-3] 

414 desc = {"description": "", "status": "", "name": mod} 

415 with io.open(f, errors="replace") as fd: 

416 for line in fd: 

417 if line[0] != "#": 

418 continue 

419 p = line.find("scapy.contrib.") 

420 if p >= 0: 

421 p += 14 

422 q = line.find("=", p) 

423 key = line[p:q].strip() 

424 value = line[q + 1:].strip() 

425 desc[key] = value 

426 if desc["status"] == "skip": 

427 break 

428 if desc["description"] and desc["status"]: 

429 results.append(desc) 

430 break 

431 if _debug: 

432 if desc["status"] == "skip": 

433 pass 

434 elif not desc["description"] or not desc["status"]: 

435 raise Scapy_Exception("Module %s is missing its " 

436 "contrib infos !" % mod) 

437 results.sort(key=lambda x: x["name"]) 

438 if ret: 

439 return results 

440 else: 

441 for desc in results: 

442 print("%(name)-20s: %(description)-40s status=%(status)s" % desc) 

443 return None 

444 

445 

446def _scapy_prestart_builtins(): 

447 # type: () -> Dict[str, Any] 

448 """Load Scapy prestart and return all builtins""" 

449 return { 

450 k: v 

451 for k, v in importlib.import_module(".config", "scapy").__dict__.copy().items() 

452 if _validate_local(k) 

453 } 

454 

455 

456def _scapy_builtins(): 

457 # type: () -> Dict[str, Any] 

458 """Load Scapy and return all builtins""" 

459 return { 

460 k: v 

461 for k, v in importlib.import_module(".all", "scapy").__dict__.copy().items() 

462 if _validate_local(k) 

463 } 

464 

465 

466def _scapy_exts(): 

467 # type: () -> Dict[str, Any] 

468 """Load Scapy exts and return their builtins""" 

469 from scapy.config import conf 

470 res = {} 

471 for modname, spec in conf.exts.all_specs.items(): 

472 if spec.default: 

473 mod = sys.modules[modname] 

474 res.update({ 

475 k: v 

476 for k, v in mod.__dict__.copy().items() 

477 if _validate_local(k) 

478 }) 

479 return res 

480 

481 

482@overload 

483def init_session(mydict, # type: Optional[Union[Dict[str, Any], None]] 

484 ret, # type: Literal[True] 

485 ): 

486 # type: (...) -> Dict[str, Any] 

487 pass 

488 

489 

490@overload 

491def init_session(mydict=None, # type: Optional[Union[Dict[str, Any], None]] 

492 ret=False, # type: Literal[False] 

493 ): 

494 # type: (...) -> None 

495 pass 

496 

497 

498def init_session(mydict=None, # type: Optional[Union[Dict[str, Any], None]] 

499 ret=False, # type: bool 

500 ): 

501 # type: (...) -> Union[Dict[str, Any], None] 

502 from scapy.config import conf 

503 

504 # Load Scapy 

505 scapy_builtins = _scapy_builtins() 

506 

507 # Load exts 

508 scapy_builtins.update(_scapy_exts()) 

509 

510 SESSION = {"conf": conf} # type: Dict[str, Any] 

511 SESSION.update(scapy_builtins) 

512 

513 if mydict is not None: 

514 SESSION.update(mydict) 

515 if ret: 

516 return SESSION 

517 return None 

518 

519 

520################ 

521# Main # 

522################ 

523 

524 

525def _prepare_quote(quote, author, max_len=78): 

526 # type: (str, str, int) -> List[str] 

527 """This function processes a quote and returns a string that is ready 

528to be used in the fancy banner. 

529 

530 """ 

531 _quote = quote.split(' ') 

532 max_len -= 6 

533 lines = [] 

534 cur_line = [] # type: List[str] 

535 

536 def _len(line): 

537 # type: (List[str]) -> int 

538 return sum(len(elt) for elt in line) + len(line) - 1 

539 while _quote: 

540 if not cur_line or (_len(cur_line) + len(_quote[0]) - 1 <= max_len): 

541 cur_line.append(_quote.pop(0)) 

542 continue 

543 lines.append(' | %s' % ' '.join(cur_line)) 

544 cur_line = [] 

545 if cur_line: 

546 lines.append(' | %s' % ' '.join(cur_line)) 

547 cur_line = [] 

548 lines.append(' | %s-- %s' % (" " * (max_len - len(author) - 5), author)) 

549 return lines 

550 

551 

552def get_fancy_banner(mini: Optional[bool] = None) -> str: 

553 """ 

554 Generates the fancy Scapy banner 

555 

556 :param mini: if set, force a mini banner or not. Otherwise detect 

557 """ 

558 from scapy.config import conf 

559 from scapy.utils import get_terminal_width 

560 if mini is None: 

561 mini_banner = (get_terminal_width() or 84) <= 75 

562 else: 

563 mini_banner = mini 

564 

565 the_logo = [ 

566 " ", 

567 " aSPY//YASa ", 

568 " apyyyyCY//////////YCa ", 

569 " sY//////YSpcs scpCY//Pp ", 

570 " ayp ayyyyyyySCP//Pp syY//C ", 

571 " AYAsAYYYYYYYY///Ps cY//S", 

572 " pCCCCY//p cSSps y//Y", 

573 " SPPPP///a pP///AC//Y", 

574 " A//A cyP////C", 

575 " p///Ac sC///a", 

576 " P////YCpc A//A", 

577 " scccccp///pSP///p p//Y", 

578 " sY/////////y caa S//P", 

579 " cayCyayP//Ya pY/Ya", 

580 " sY/PsY////YCc aC//Yp ", 

581 " sc sccaCY//PCypaapyCP//YSs ", 

582 " spCPY//////YPSps ", 

583 " ccaacs ", 

584 " ", 

585 ] 

586 

587 # Used on mini screens 

588 the_logo_mini = [ 

589 " .SYPACCCSASYY ", 

590 "P /SCS/CCS ACS", 

591 " /A AC", 

592 " A/PS /SPPS", 

593 " YP (SC", 

594 " SPS/A. SC", 

595 " Y/PACC PP", 

596 " PY*AYC CAA", 

597 " YYCY//SCYP ", 

598 ] 

599 

600 the_banner = [ 

601 "", 

602 "", 

603 " |", 

604 " | Welcome to Scapy", 

605 " | Version %s" % conf.version, 

606 " |", 

607 " | https://github.com/secdev/scapy", 

608 " |", 

609 " | Have fun!", 

610 " |", 

611 ] 

612 

613 if mini_banner: 

614 the_logo = the_logo_mini 

615 the_banner = [x[2:] for x in the_banner[3:-1]] 

616 the_banner = [""] + the_banner + [""] 

617 else: 

618 quote, author = choice(QUOTES) 

619 the_banner.extend(_prepare_quote(quote, author, max_len=39)) 

620 the_banner.append(" |") 

621 return "\n".join( 

622 logo + banner for logo, banner in zip_longest( 

623 (conf.color_theme.logo(line) for line in the_logo), 

624 (conf.color_theme.success(line) for line in the_banner), 

625 fillvalue="" 

626 ) 

627 ) 

628 

629 

630def interact(mydict=None, 

631 argv=None, 

632 mybanner=None, 

633 mybanneronly=False, 

634 loglevel=logging.INFO): 

635 # type: (Optional[Any], Optional[Any], Optional[Any], bool, int) -> None 

636 """ 

637 Starts Scapy's console. 

638 """ 

639 # We're in interactive mode, let's throw the DeprecationWarnings 

640 warnings.simplefilter("always") 

641 

642 # Set interactive mode, load the color scheme 

643 from scapy.config import conf 

644 conf.interactive = True 

645 conf.color_theme = DefaultTheme() 

646 if loglevel is not None: 

647 conf.logLevel = loglevel 

648 

649 STARTUP_FILE = DEFAULT_STARTUP_FILE 

650 PRESTART_FILE = DEFAULT_PRESTART_FILE 

651 

652 if argv is None: 

653 argv = sys.argv 

654 

655 try: 

656 opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d:H") 

657 for opt, param in opts[0]: 

658 if opt == "-h": 

659 _usage() 

660 elif opt == "-H": 

661 conf.fancy_banner = False 

662 conf.verb = 1 

663 conf.logLevel = logging.WARNING 

664 elif opt == "-c": 

665 STARTUP_FILE = param 

666 elif opt == "-C": 

667 STARTUP_FILE = None 

668 elif opt == "-p": 

669 PRESTART_FILE = param 

670 elif opt == "-P": 

671 PRESTART_FILE = None 

672 elif opt == "-d": 

673 conf.logLevel = max(1, conf.logLevel - 10) 

674 

675 if len(opts[1]) > 0: 

676 raise getopt.GetoptError( 

677 "Too many parameters : [%s]" % " ".join(opts[1]) 

678 ) 

679 

680 except getopt.GetoptError as msg: 

681 log_loading.error(msg) 

682 sys.exit(1) 

683 

684 # Reset sys.argv, otherwise IPython thinks it is for him 

685 sys.argv = sys.argv[:1] 

686 

687 if PRESTART_FILE: 

688 _read_config_file( 

689 PRESTART_FILE, 

690 interactive=True, 

691 _locals=_scapy_prestart_builtins(), 

692 default=DEFAULT_PRESTART, 

693 ) 

694 

695 SESSION = init_session(mydict=mydict, ret=True) 

696 

697 if STARTUP_FILE: 

698 _read_config_file( 

699 STARTUP_FILE, 

700 interactive=True, 

701 _locals=SESSION 

702 ) 

703 

704 # Load extensions (Python 3.8 Only) 

705 if sys.version_info >= (3, 8): 

706 conf.exts.loadall() 

707 

708 if conf.fancy_banner: 

709 banner_text = get_fancy_banner() 

710 else: 

711 banner_text = "Welcome to Scapy (%s)" % conf.version 

712 

713 # Make sure the history file has proper permissions 

714 try: 

715 if not pathlib.Path(conf.histfile).exists(): 

716 pathlib.Path(conf.histfile).touch() 

717 _check_perms(conf.histfile) 

718 except OSError: 

719 pass 

720 

721 # Configure interactive terminal 

722 

723 if conf.interactive_shell not in [ 

724 "ipython", 

725 "python", 

726 "ptpython", 

727 "ptipython", 

728 "bpython", 

729 "auto"]: 

730 log_loading.warning("Unknown conf.interactive_shell ! Using 'auto'") 

731 conf.interactive_shell = "auto" 

732 

733 # Auto detect available shells. 

734 # Order: 

735 # 1. IPython 

736 # 2. bpython 

737 # 3. ptpython 

738 

739 _IMPORTS = { 

740 "ipython": ["IPython"], 

741 "bpython": ["bpython"], 

742 "ptpython": ["ptpython"], 

743 "ptipython": ["IPython", "ptpython"], 

744 } 

745 

746 if conf.interactive_shell == "auto": 

747 # Auto detect 

748 for imp in ["IPython", "bpython", "ptpython"]: 

749 try: 

750 importlib.import_module(imp) 

751 conf.interactive_shell = imp.lower() 

752 break 

753 except ImportError: 

754 continue 

755 else: 

756 log_loading.warning( 

757 "No alternative Python interpreters found ! " 

758 "Using standard Python shell instead." 

759 ) 

760 conf.interactive_shell = "python" 

761 

762 if conf.interactive_shell in _IMPORTS: 

763 # Check import 

764 for imp in _IMPORTS[conf.interactive_shell]: 

765 try: 

766 importlib.import_module(imp) 

767 except ImportError: 

768 log_loading.warning("%s requested but not found !" % imp) 

769 conf.interactive_shell = "python" 

770 

771 # Default shell 

772 if conf.interactive_shell == "python": 

773 disabled = ["History"] 

774 if WINDOWS: 

775 disabled.append("Colors") 

776 conf.color_theme = BlackAndWhite() 

777 else: 

778 try: 

779 # Bad completer.. but better than nothing 

780 import rlcompleter 

781 import readline 

782 readline.set_completer( 

783 rlcompleter.Completer(namespace=SESSION).complete 

784 ) 

785 readline.parse_and_bind('tab: complete') 

786 except ImportError: 

787 disabled.insert(0, "AutoCompletion") 

788 # Display warning when using the default REPL 

789 log_loading.info( 

790 "Using the default Python shell: %s %s disabled." % ( 

791 ",".join(disabled), 

792 "is" if len(disabled) == 1 else "are" 

793 ) 

794 ) 

795 

796 # ptpython configure function 

797 def ptpython_configure(repl): 

798 # type: (Any) -> None 

799 # Hide status bar 

800 repl.show_status_bar = False 

801 # Complete while typing (versus only when pressing tab) 

802 repl.complete_while_typing = False 

803 # Enable auto-suggestions 

804 repl.enable_auto_suggest = True 

805 # Disable exit confirmation 

806 repl.confirm_exit = False 

807 # Show signature 

808 repl.show_signature = True 

809 # Apply Scapy color theme: TODO 

810 # repl.install_ui_colorscheme("scapy", 

811 # Style.from_dict(_custom_ui_colorscheme)) 

812 # repl.use_ui_colorscheme("scapy") 

813 

814 # Extend banner text 

815 banner = banner_text 

816 if conf.interactive_shell in ["ipython", "ptipython"]: 

817 import IPython 

818 if conf.interactive_shell == "ptipython": 

819 banner = banner_text + " using IPython %s" % IPython.__version__ 

820 try: 

821 from importlib.metadata import version 

822 ptpython_version = " " + version('ptpython') 

823 except ImportError: 

824 ptpython_version = "" 

825 banner += " and ptpython%s" % ptpython_version 

826 else: 

827 banner = banner_text + " using IPython %s" % IPython.__version__ 

828 elif conf.interactive_shell == "ptpython": 

829 try: 

830 from importlib.metadata import version 

831 ptpython_version = " " + version('ptpython') 

832 except ImportError: 

833 ptpython_version = "" 

834 banner = banner_text + " using ptpython%s" % ptpython_version 

835 elif conf.interactive_shell == "bpython": 

836 import bpython 

837 banner = banner_text + " using bpython %s" % bpython.__version__ 

838 

839 if mybanner is not None: 

840 if mybanneronly: 

841 banner = "" 

842 banner += "\n" 

843 banner += mybanner 

844 

845 # Start IPython or ptipython 

846 if conf.interactive_shell in ["ipython", "ptipython"]: 

847 banner += "\n" 

848 if conf.interactive_shell == "ptipython": 

849 from ptpython.ipython import embed 

850 else: 

851 from IPython import embed 

852 try: 

853 from traitlets.config.loader import Config 

854 except ImportError: 

855 log_loading.warning( 

856 "traitlets not available. Some Scapy shell features won't be " 

857 "available." 

858 ) 

859 try: 

860 embed( 

861 display_banner=False, 

862 user_ns=SESSION, 

863 exec_lines=["print(\"\"\"" + banner + "\"\"\")"] 

864 ) 

865 except Exception: 

866 code.interact(banner=banner_text, local=SESSION) 

867 else: 

868 cfg = Config() 

869 try: 

870 from IPython import get_ipython 

871 if not get_ipython(): 

872 raise ImportError 

873 except ImportError: 

874 # Set "classic" prompt style when launched from 

875 # run_scapy(.bat) files Register and apply scapy 

876 # color+prompt style 

877 apply_ipython_style(shell=cfg.InteractiveShellEmbed) 

878 cfg.InteractiveShellEmbed.confirm_exit = False 

879 cfg.InteractiveShellEmbed.separate_in = u'' 

880 if int(IPython.__version__[0]) >= 6: 

881 cfg.InteractiveShellEmbed.term_title = True 

882 cfg.InteractiveShellEmbed.term_title_format = ("Scapy %s" % 

883 conf.version) 

884 # As of IPython 6-7, the jedi completion module is a dumpster 

885 # of fire that should be scrapped never to be seen again. 

886 # This is why the following defaults to False. Feel free to hurt 

887 # yourself (#GH4056) :P 

888 cfg.Completer.use_jedi = conf.ipython_use_jedi 

889 else: 

890 cfg.InteractiveShellEmbed.term_title = False 

891 cfg.HistoryAccessor.hist_file = conf.histfile 

892 cfg.InteractiveShell.banner1 = banner 

893 if conf.verb < 2: 

894 cfg.InteractiveShellEmbed.enable_tip = False 

895 # configuration can thus be specified here. 

896 _kwargs = {} 

897 if conf.interactive_shell == "ptipython": 

898 _kwargs["configure"] = ptpython_configure 

899 try: 

900 embed(config=cfg, user_ns=SESSION, **_kwargs) 

901 except (AttributeError, TypeError): 

902 code.interact(banner=banner_text, local=SESSION) 

903 # Start ptpython 

904 elif conf.interactive_shell == "ptpython": 

905 # ptpython has special, non-default handling of __repr__ which breaks Scapy. 

906 # For instance: >>> IP() 

907 log_loading.warning("ptpython support is currently partially broken") 

908 from ptpython.repl import embed 

909 # ptpython has no banner option 

910 banner += "\n" 

911 print(banner) 

912 embed( 

913 locals=SESSION, 

914 history_filename=conf.histfile, 

915 title="Scapy %s" % conf.version, 

916 configure=ptpython_configure 

917 ) 

918 # Start bpython 

919 elif conf.interactive_shell == "bpython": 

920 from bpython.curtsies import main as embed 

921 embed( 

922 args=["-q", "-i"], 

923 locals_=SESSION, 

924 banner=banner, 

925 welcome_message="" 

926 ) 

927 # Start Python 

928 elif conf.interactive_shell == "python": 

929 code.interact(banner=banner_text, local=SESSION) 

930 else: 

931 raise ValueError("Invalid conf.interactive_shell") 

932 

933 

934if __name__ == "__main__": 

935 interact()