def run(self, line): def _formatOutput(res): if isinstance(res, str): return res else: try: return "\n".join(_formatOutput(r) for r in res) except TypeError: return str(res) ishellCompleter = readline.get_completer() readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(completer.complete) filePath = raw_input("Please specify a path to the output file: ").strip() readline.set_completer(ishellCompleter) if os.path.isfile(filePath): confirm = raw_input("File already exists and will be overwritten, confirm? [y/N] ") if confirm is "" or confirm[0] not in ("y", "Y"): print "Canceled." return with open(filePath, "w+") as handle: handle.write(_formatOutput(feathermodules.results))
def cmdloop(self, intro=None): self.old_completer = readline.get_completer() self.old_completer_delims = readline.get_completer_delims() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey+": complete") readline.parse_and_bind("set bell-style none") readline.parse_and_bind("set show-all-if-ambiguous") readline.parse_and_bind("set completion-query-items -1") # If press help key, add the character and accept the line readline.parse_and_bind('"?": "\C-q?\C-j"') # Register a function for execute before read user # input. We can use it for insert text at command line readline.set_pre_input_hook(self.pre_input_hook) readline.set_completer_delims(' \t\n') try: stop = None while not stop: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' stop = self.onecmd(line) stop = self.postcmd(stop, line) finally: readline.set_completer(self.old_completer) readline.set_completer_delims(self.old_completer_delims)
def __init__(self): Cmd.__init__(self) try: import readline readline.set_completer_delims(' \t\n"') # initially it was ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?', but I dont want to break on too many except: pass
def launch_ui(args): # Setup tab completion try: import readline except ImportError: print('%s[!] Module \'readline\' not available. Tab complete disabled.%s' % (Colors.R, Colors.N)) else: import rlcompleter if 'libedit' in readline.__doc__: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') readline.set_completer_delims(re.sub('[/-]', '', readline.get_completer_delims())) # Instantiate the UI object x = cli.CLI(cli.Mode.CONSOLE) # check for and run version check if args.check: if not x.version_check(): return # Check for and run script session if args.script_file: x.do_resource(args.script_file) # Run the UI try: x.cmdloop() except KeyboardInterrupt: print('')
def main(self, argv): cmd_args = argv[1:] if cmd_args: cmd_line = u' '.join(cmd_args) cmds = cmd_line.split(';') for cmd in cmds: ret = self.onecmd(cmd) if ret: return ret elif self.DISABLE_REPL: self._parser.print_help() self._parser.exit() else: try: import readline except ImportError: pass else: # Remove '-' from delims readline.set_completer_delims(readline.get_completer_delims().replace('-', '')) history_filepath = os.path.join(self.weboob.workdir, '%s_history' % self.APPNAME) try: readline.read_history_file(history_filepath) except IOError: pass def savehist(): readline.write_history_file(history_filepath) atexit.register(savehist) self.intro += '\nLoaded backends: %s\n' % ', '.join(sorted(backend.name for backend in self.weboob.iter_backends())) self._interactive = True self.cmdloop()
def h5py_item_completer(context, command): """Compute possible item matches for dict-like objects""" base, item = re_item_match.split(command)[1:4:2] # we don't want to call any functions, but I couldn't find a robust regex # that filtered them without unintended side effects. So keys containing # "(" will not complete. try: assert '(' not in base except AssertionError: raise ValueError() try: obj = eval(base, context.shell.user_ns) except: return [] path, target = posixpath.split(item) if path: items = (posixpath.join(path, name) for name in obj[path].iterkeys()) else: items = obj.iterkeys() items = list(items) readline.set_completer_delims(' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?') return [i for i in items if i[:len(item)] == item]
def h5py_attr_completer(context, command): """Compute possible attr matches for nested dict-like objects""" base, attr = re_attr_match.split(command)[1:3] base = base.strip() try: assert '(' not in base except AssertionError: raise ValueError() try: obj = eval(base, context.shell.user_ns) except: return [] attrs = dir(obj) try: attrs = generics.complete_object(obj, attrs) except TryNext: pass try: omit__names = ipget().readline_omit__names except AttributeError: # support <ipython-0.11 omit__names = ipget().options.readline_omit__names if omit__names == 1: attrs = [a for a in attrs if not a.startswith('__')] elif omit__names == 2: attrs = [a for a in attrs if not a.startswith('_')] readline.set_completer_delims(' =') return ["%s.%s" % (base, a) for a in attrs if a[:len(attr)] == attr]
def interact(PS1, PS2, BANNER, *arg, **kwarg): def Completer(text, stat): if text.startswith('.') or text.startswith('/'): ret = path_matches(text) elif '.' not in text: ret = global_matches(text) else: ret = attr_matches(text) try: return ret[stat] except IndexError: return None @utils.regExitCallback def exit_interact(): """ Clean all when exit """ print "Goodbye..." ## Compatible for Mac OS since Mac OS ship libedit for readline if "libedit" in readline.__doc__: import rlcompleter readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") ## Change PS sys.ps1, sys.ps2 = PS1, PS2 delims = readline.get_completer_delims().replace('/','') readline.set_completer_delims(delims) readline.set_completer(Completer) ## Run Interpreter code.interact(banner=BANNER, local=globals())
def file_chooser(prompt_text = "Enter File: ", default=None, filearg=[], filekwarg={}): """A simple tool to get a file from the user. Takes keyworded arguemnts and passes them to open(). If the user enters nothing the function will return the ``default`` value. Otherwise it continues to prompt the user until it get's a decent response. filekwarg may contain arguements passed on to ``open()``. """ try: import readline, rlcomplete completer = rlcomplete.PathCompleter() readline.set_completer_delims(completer.delims) readline.parse_and_bind("tab: complete") readline.set_completer(completer.complete) except ImportError: pass while True: f = raw_input(prompt_text) if f == '': return default f = os.path.expanduser(f) if len(f) != 0 and f[0] == os.path.sep: f = os.path.abspath(f) try: return open(f, *filearg, **filekwarg) except IOError, e: stderr.write(ERROR_MESSAGE % ("unable to open %s : %s" % (f, e)))
def main(): global __prompt global __time_to_go print("JSON configuration utility version (1.0.0)") handle_arguments() readline.set_completer_delims("\t\n") readline.parse_and_bind("tab: complete") readline.set_completer(auto_complete) command = "" while True: try: user_input = input(__prompt + " ").strip() except KeyboardInterrupt: print() if __time_to_go: exit_command() else: __time_to_go = True print("Press ^C again to close. Running another command resets this.") continue if not user_input: continue run_command(user_input) __time_to_go = False
def main(files=[]): printtty(colorize('> ', PROMPT_COLOR) + "; Type HELP to get the HELP") printtty(colorize('> ', PROMPT_COLOR) + "; Completion is activated using the tab (if supported by the terminal)") for i in files: load_relation(i) readline.set_completer(completer.complete) readline.parse_and_bind('tab: complete') readline.parse_and_bind('set editing-mode emacs') readline.set_completer_delims(" ") while True: try: line = input(colorize('> ' if TTY else '', PROMPT_COLOR)) if isinstance(line, str) and len(line) > 0: exec_line(line) except KeyboardInterrupt: if TTY: print ('^C\n') continue else: break except EOFError: printtty() sys.exit(0)
def completer(self,func): def keys(): keys = [i for i in func()] return keys readline.set_completer(SimpleCompleter(keys()).complete) readline.set_completer_delims('') readline.parse_and_bind('tab: complete')
def exec_cmdloop(self, args, options): try: import readline delims = readline.get_completer_delims() delims = delims.replace(':', '') # "group:process" as one word delims = delims.replace('*', '') # "group:*" as one word delims = delims.replace('-', '') # names with "-" as one word readline.set_completer_delims(delims) if options.history_file: try: readline.read_history_file(options.history_file) except IOError: pass def save(): try: readline.write_history_file(options.history_file) except IOError: pass import atexit atexit.register(save) except ImportError: pass try: self.cmdqueue.append('status') self.cmdloop() except KeyboardInterrupt: self.output('') pass
def rlinput(prompt, prefill='', oneline=False, ctxkey=''): """ Get user input with readline editing support. """ sentinel = '' if prefill is None: prefill = '' def only_once(text): """ generator for startup hook """ readline.insert_text(text) yield while True: yield savedhist = NamedTemporaryFile() readline.write_history_file(savedhist.name) ctxhistname = ".tl" + ctxkey + "history" ctxhistfile = os.path.join(G.ProjectFolder, ctxhistname) try: readline.clear_history() except AttributeError: print "This readline doesn't support clear_history()" raise savedcompleter = readline.get_completer() try: ulines = uniqify(ctxhistfile) readline.read_history_file(ctxhistfile) readline.set_completer(HistoryCompleter(ulines).complete) except IOError: pass readline.parse_and_bind('tab: complete') saveddelims = readline.get_completer_delims() readline.set_completer_delims('') ## No delims. Complete entire lines. readline.set_completion_display_matches_hook(match_display_hook) gen = only_once(prefill) readline.set_startup_hook(gen.next) try: if oneline: edited = raw_input(prompt) else: print prompt edited = "\n".join(iter(raw_input, sentinel)) if edited.endswith(r'%%'): ## Invoke external editor edited = external_edit(edited[0:-2]) return edited finally: ## Restore readline state readline.write_history_file(ctxhistfile) readline.clear_history() readline.read_history_file(savedhist.name) savedhist.close() readline.set_completer(savedcompleter) readline.set_completer_delims(saveddelims) readline.set_startup_hook()
def sshcheck(): attacks = {} users = {} try: import readline, rlcompleter readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete) except ImportError: print 'No Tab Completion' LOGs = raw_input('Enter the path to the log file: ') for LOG in LOGs.split(' '): if LOG.endswith('.gz'): auth_logs = gzip.GzipFile(LOG, 'r') else: auth_logs = open(LOG, 'r') if len(LOGs) is '1': print "Parsing log file" else: print "Parsing log files" for log in auth_logs: l = {"raw": log } normalizer.normalize(l) if l.get('action') == 'fail' and l.get('program') == 'sshd': u = l['user'] p = l['source_ip'] o1, o2, o3, o4 = [int(i) for i in p.split('.')] if o1 == 192 and o2 == 168 or o1 == 172 and o2 in range(16, 32) or o1 == 10: print "Private IP, %s No geolocation data" %str(p) attacks[p] = attacks.get(p, 0) + 1 getip() dojson(attacks, IP)
def shell(): print "Welcome to DQuery 0.2, enjoy SQL and DPark! type 'help' for help." sql = '' import readline readline.set_completer_delims(' \t\n;') readline.parse_and_bind('tab: complete') readline.set_completer(complete) while True: try: if sql: sql += raw_input('... ') else: sql = raw_input('>>> ') except EOFError: break try: cmd = sql.split(' ')[0] if cmd in CMDS: if sql not in CMDS and not sql.endswith(';'): continue execute(sql) if sql.split(' ')[0].lower() in REMEMBER_CMDS: remember(sql) elif ('\n' not in sql and not sql.endswith(':')) or ('\n' in sql and sql.endswith('\n')): exec sql in globals(), _locals # python else: sql += '\n' continue except Exception, e: import traceback; traceback.print_exc() sql = ''
def setup(self): """ Initialization of third-party libraries Setting interpreter history. Setting appropriate completer function. :return: """ if not os.path.exists(self.history_file): with open(self.history_file, 'a+') as history: if is_libedit(): history.write("_HiStOrY_V2_\n\n") readline.read_history_file(self.history_file) readline.set_history_length(self.history_length) atexit.register(readline.write_history_file, self.history_file) readline.parse_and_bind('set enable-keypad on') readline.set_completer(self.complete) readline.set_completer_delims(' \t\n;') if is_libedit(): readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete")
def run(json): global __exit, __prompt readline.set_completer_delims("\t") readline.parse_and_bind("tab: complete") readline.set_completer(autocomplete) while True: action = "" try: line = input("{}".format(__prompt)).strip() except KeyboardInterrupt: if __exit: sys.exit(0) else: print("Press ^C again to quit. Otherwise run another command.") __exit = True continue if not line: continue try: interpret(line)(json=json) except (NotImplementedError, TypeError, AttributeError, ValueError) as e: print(e) __exit = False
def _reset_readline(): if readline: readline.parse_and_bind("tab: complete") readline.parse_and_bind("set horizontal-scroll-mode on") readline.parse_and_bind("set page-completions on") readline.set_completer_delims(" ") readline.set_history_length(500)
def sftp_cmd(*args): sftp = Channel.get_instance().get_transport().open_sftp_client() old_completer = readline.get_completer() readline.set_completer(sftp_completer(sftp)) old_delim = readline.get_completer_delims() readline.set_completer_delims(' /') global rcwd try: try: cmd = raw_input('SFTP> ') except EOFError: return except KeyboardInterrupt: return while not cmd or not 'quit'.startswith(cmd): args = [x for x in cmd.split(' ') if x] if args and args[0] in all_cmd: all_cmd[args[0]](sftp, args) else: print('invalid command') try: cmd = raw_input('SFTP> ') except EOFError: return except KeyboardInterrupt: return finally: readline.set_completer(old_completer) readline.set_completer_delims(old_delim)
def export_gcal(v, y, m, d, tid, sid): cmd = [] cmd.append("gcalcli") cmd.append("--calendar") readline.set_startup_hook(lambda: readline.insert_text("")) t = tabCompleter() t.createListCompleter(["calender", "NSC absences", "NSC shared calender"]) readline.set_completer_delims('\t') readline.parse_and_bind("tab: complete") readline.set_completer(t.listCompleter) calender = raw_input("Name of calender: ").strip() cmd.append(calender) cmd.append("--title") v[y][m][d][tid][sid]["subtask title"] cmd.append(v[y][m][d][tid][sid]["subtask title"]) cmd.append("--where") cmd.append("''") cmd.append("--when") dt = str(m)+ "/" + str(d) + "/" + str(y) + " " + v[y][m][d][tid][sid]["start"] cmd.append(dt) cmd.append("--duration") (h1, m1) = tuple(v[y][m][d][tid][sid]["start"].split(':')) (h2, m2) = tuple(v[y][m][d][tid][sid]["end"].split(':')) dur = str((int(h2) - int(h1)) * 60 + (int(m2) -int(m1))) cmd.append(dur) cmd.append("--description") cmd.append("''") cmd.append("--reminder") cmd.append("0") cmd.append("add") job = subprocess.Popen(cmd) job.wait() raw_input("Press enter to continue")
def Shell(user_session): # This should bring back the old autocall behaviour. e.g.: # In [1]: pslist cfg = Config() cfg.InteractiveShellEmbed.autocall = 2 cfg.TerminalInteractiveShell.prompts_class = RekallPrompt cfg.InteractiveShell.separate_in = '' cfg.InteractiveShell.separate_out = '' cfg.InteractiveShell.separate_out2 = '' shell = RekallShell(config=cfg, user_ns=user_session.locals) shell.Completer.merge_completions = False shell.exit_msg = constants.GetQuote() shell.set_custom_completer(RekallCompleter, 0) # Do we need to pre-run something? if user_session.run != None: execfile(user_session.run, user_session.locals) user_session.shell = shell # Set known delimeters for the completer. This varies by OS so we need to # set it to ensure consistency. readline.set_completer_delims(' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?') for magic in REGISTERED_MAGICS: shell.register_magics(magic) shell(module=user_session.locals, ) return True
def set_completer(options=None): if options: completer = InputCompleter(options) readline.set_completer(completer.complete) readline.set_completer_delims('') else: readline.set_completer(None)
def run_shell(self): '''Run shell.''' run = 1 self.load_shell_history() readline.parse_and_bind('tab: complete') readline.set_completer(self.shell_completer2) readline.set_completer_delims( ' \t\n`~!@#$%^&*()=+[{]}\\|;:\'",<>/?') while run: try: comm = raw_input("# ") except EOFError: print('') sys.exit(0) self.simple_parse(comm) if comm == 'quit': run = 0 return
def run(self, script_file=None): """Run the python interpreter. The namespace of this function is the namespace seen inside the interpreter. All user accessible functions, classes, etc, should be placed in this namespace. @param script_file: The script file to be executed. For the interpreter mode, this should be left as None. @type script_file: None or str """ # Add the interpreter objects to the local run namespace. for name in self._locals.keys(): locals()[name] = self._locals[name] # Setup tab completion. if dep_check.readline_module: readline.set_completer(Tab_completion(name_space=locals()).finish) readline.set_completer_delims(' \t\n`~!@#$%^&*()=+{}\\|;:",<>/?') readline.parse_and_bind("tab: complete") # Execute the script file if given. if script_file: # Turn on the user function intro flag. status.uf_intro = True # Run the script. return run_script(intro=self.__intro_string, local=locals(), script_file=script_file, quit=self.__quit_flag, show_script=self.__show_script, raise_relax_error=self.__raise_relax_error) # Go to the prompt. else: prompt(intro=self.__intro_string, local=locals())
def interactive(self): print "Command list: " + ", ".join(self.cmd_list) try: readline.set_completer(SuricataCompleter(self.cmd_list)) readline.set_completer_delims(";") readline.parse_and_bind('tab: complete') while True: command = raw_input(">>> ").strip() if command == "quit": break; try: (cmd, arguments) = self.parse_command(command) except SuricataCommandException, err: print err continue cmdret = self.send_command(cmd, arguments) #decode json message if cmdret["return"] == "NOK": print "Error:" print json.dumps(cmdret["message"], sort_keys=True, indent=4, separators=(',', ': ')) else: print "Success:" print json.dumps(cmdret["message"], sort_keys=True, indent=4, separators=(',', ': ')) except KeyboardInterrupt: print "[!] Interrupted"
def __init__(self, admin_cli): # remove stdout stream encoding while in 'shell' mode, becuase this breaks readline # (autocompletion and shell history). In 'shell' mode the stdout # is encoded just for time necessary for command execution see precmd a postcmd sys.stdout = stdout_origin self.stdout_with_codec = encode_stream(sys.stdout, "utf-8") self.completion_matches = None Cmd.__init__(self) self.admin_cli = admin_cli self.completion = Completion(self.admin_cli) try: Config() self.prompt = Config.parser.get('shell', 'prompt') + ' ' except (ConfigFileError, ConfigParser.Error): self.prompt = 'katello> ' try: # don't split on hyphens during tab completion (important for completing parameters) newdelims = readline.get_completer_delims() newdelims = re.sub('-', '', newdelims) readline.set_completer_delims(newdelims) if (Config.parser.get('shell', 'nohistory').lower() != 'true'): self.__init_history() except ConfigParser.Error: pass self.__init_commands()
def __init__(self, command_line): self.status = {} self.status['log_started'] = False self.status['resource_found'] = False self.status['command_line'] = command_line self.status['file_found'] = False self.global_config = {} self.tools = [] self.assessments = [] self.job_queue = [] self.arguments = ddict_options = defaultdict(lambda : '') self.instance = {} self.instance['tool'] = [] self.instance['config'] = {} self.load("tools") self.load("assessments") self.load("global_config") # Remove / from completer delim so tab completion works # with tool/nmap, for example old_delims = readline.get_completer_delims() readline.set_completer_delims(old_delims.replace('/', ''))
def __init__(self): main = sys.modules.pop('__main__') try: self.dummy_main = new.module('__main__') sys.modules['__main__'] = self.dummy_main from rlcompleter import Completer as RlCompleter self.python_completer = RlCompleter() finally: sys.modules['__main__'] = main readline.set_completer_delims(' \t\n;`\"()') readline.parse_and_bind('tab: complete') readline.set_completer(self.complete) base_dir = os.path.expanduser('~/.dq') if not os.path.exists(base_dir): try: os.mkdir(base_dir) except IOError: pass hist_file = os.path.join(base_dir, 'hist') try: readline.read_history_file(hist_file) except IOError: pass atexit.register(readline.write_history_file, hist_file) init_file = os.path.join(base_dir, 'init') if os.path.exists(init_file): with open(init_file, 'r') as f: self.run_script(f.read()) self.sql = ''
def setup_readline(): """Sets up the readline module and completion supression, if available.""" global RL_COMPLETION_SUPPRESS_APPEND, RL_LIB, RL_CAN_RESIZE if RL_COMPLETION_SUPPRESS_APPEND is not None: return try: import readline except ImportError: return import ctypes import ctypes.util readline.set_completer_delims(' \t\n') RL_LIB = lib = ctypes.cdll.LoadLibrary(readline.__file__) try: RL_COMPLETION_SUPPRESS_APPEND = ctypes.c_int.in_dll( lib, 'rl_completion_suppress_append') except ValueError: # not all versions of readline have this symbol, ie Macs sometimes RL_COMPLETION_SUPPRESS_APPEND = None RL_CAN_RESIZE = hasattr(lib, 'rl_reset_screen_size') # reads in history env = builtins.__xonsh_env__ # sets up IPython-like history matching with up and down readline.parse_and_bind('"\e[B": history-search-forward') readline.parse_and_bind('"\e[A": history-search-backward') # Setup Shift-Tab to indent readline.parse_and_bind('"\e[Z": "{0}"'.format(env.get('INDENT', ''))) # handle tab completion differences found in libedit readline compatibility # as discussed at http://stackoverflow.com/a/7116997 if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete")
def __init__(self, preferences_dir=None): ''' Creates a new ConfigShell. @param preferences_dir: Directory to load/save preferences from/to @type preferences_dir: str ''' self._current_node = None self._root_node = None self._exit = False # Grammar of the command line command = locatedExpr(Word(alphanums + '_'))('command') var = Word(alphanums + '_\+/.<>()~@:-%[]') value = var keyword = Word(alphanums + '_\-') kparam = locatedExpr(keyword + Suppress('=') + Optional(value, default=''))('kparams*') pparam = locatedExpr(var)('pparams*') parameter = kparam | pparam parameters = OneOrMore(parameter) bookmark = Regex('@([A-Za-z0-9:_.]|-)+') pathstd = Regex('([A-Za-z0-9:_.]|-)*' + '/' + '([A-Za-z0-9:_./]|-)*') \ | '..' | '.' path = locatedExpr(bookmark | pathstd | '*')('path') parser = Optional(path) + Optional(command) + Optional(parameters) self._parser = parser if tty: readline.set_completer_delims('\t\n ~!#$^&(){}\|;\'",?') readline.set_completion_display_matches_hook( self._display_completions) self.log = log.Log() if preferences_dir is not None: preferences_dir = os.path.expanduser(preferences_dir) if not os.path.exists(preferences_dir): os.makedirs(preferences_dir) self._prefs_file = preferences_dir + '/prefs.bin' self.prefs = prefs.Prefs(self._prefs_file) self._cmd_history = preferences_dir + '/history.txt' self._save_history = True if not os.path.isfile(self._cmd_history): try: open(self._cmd_history, 'w').close() except: self.log.warning("Cannot create history file %s, " % self._cmd_history + "command history will not be saved.") self._save_history = False if os.path.isfile(self._cmd_history) and tty: try: readline.read_history_file(self._cmd_history) except IOError: self.log.warning("Cannot read command history file %s." % self._cmd_history) if self.prefs['logfile'] is None: self.prefs['logfile'] = preferences_dir + '/' + 'log.txt' self.prefs.autosave = True else: self.prefs = prefs.Prefs() self._save_history = False try: self.prefs.load() except IOError: self.log.warning("Could not load preferences file %s." % self._prefs_file) for pref, value in six.iteritems(self.default_prefs): if pref not in self.prefs: self.prefs[pref] = value self.con = console.Console()
def __init__(self, rendezvousAddr=None, controllerNodeId=1, bluetoothAdapter=None): self.lastNetworkId = None pretty.install(indent_guides=True, expand_all=True) coloredlogs.install(level='DEBUG') chip.logging.RedirectToPythonLogging() logging.getLogger().setLevel(logging.DEBUG) warnings.showwarning = ShowColoredWarnings Cmd.__init__(self) Cmd.identchars = string.ascii_letters + string.digits + "-" if sys.stdin.isatty(): self.prompt = "chip-device-ctrl > " else: self.use_rawinput = 0 self.prompt = "" DeviceMgrCmd.command_names.sort() self.bleMgr = None self.chipStack = ChipStack.ChipStack( bluetoothAdapter=bluetoothAdapter, persistentStoragePath='/tmp/chip-device-ctrl-storage.json') self.fabricAdmin = FabricAdmin.FabricAdmin() self.devCtrl = self.fabricAdmin.NewController(controllerNodeId, True) self.commissionableNodeCtrl = ChipCommissionableNodeCtrl.ChipCommissionableNodeController( self.chipStack) # If we are on Linux and user selects non-default bluetooth adapter. if sys.platform.startswith("linux") and (bluetoothAdapter is not None): try: self.bleMgr = BleManager(self.devCtrl) self.bleMgr.ble_adapter_select( "hci{}".format(bluetoothAdapter)) except Exception as ex: traceback.print_exc() print( "Failed to initialize BLE, if you don't have BLE, run chip-device-ctrl with --no-ble" ) raise ex self.historyFileName = os.path.expanduser( "~/.chip-device-ctrl-history") try: import readline if "libedit" in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") readline.set_completer_delims(" ") try: readline.read_history_file(self.historyFileName) except IOError: pass except ImportError: pass
def __generate_ePass(self): """Generate the MF and SAM of an ICAO passport. This method is responsible for generating the filesystem and filling it with content. Therefore it must interact with the user by prompting for the MRZ and optionally for the path to a photo.""" from PIL import Image from virtualsmartcard.cards.ePass import PassportSAM # TODO: Sanity checks MRZ = raw_input("Please enter the MRZ as one string: ") readline.set_completer_delims("") readline.parse_and_bind("tab: complete") picturepath = raw_input("Please enter the path to an image: ") picturepath = picturepath.strip() # MRZ1 = "P<UTOERIKSSON<<ANNA<MARIX<<<<<<<<<<<<<<<<<<<" # MRZ2 = "L898902C<3UTO6908061F9406236ZE184226B<<<<<14" # MRZ = MRZ1 + MRZ2 try: im = Image.open(picturepath) pic_width, pic_height = im.size fd = open(picturepath, "rb") picture = fd.read() fd.close() except IOError: logging.warning("Failed to open file: " + picturepath) pic_width = 0 pic_height = 0 picture = None mf = MF() # We need a MF with Application DF \xa0\x00\x00\x02G\x10\x01 df = DF(parent=mf, fid=4, dfname='\xa0\x00\x00\x02G\x10\x01', bertlv_data=[]) # EF.COM COM = pack([(0x5F01, 4, "0107"), (0x5F36, 6, "040000"), (0x5C, 2, "6175")]) COM = pack(((0x60, len(COM), COM), )) df.append( TransparentStructureEF(parent=df, fid=0x011E, filedescriptor=0, data=COM)) # EF.DG1 DG1 = pack([(0x5F1F, len(MRZ), MRZ)]) DG1 = pack([(0x61, len(DG1), DG1)]) df.append( TransparentStructureEF(parent=df, fid=0x0101, filedescriptor=0, data=DG1)) # EF.DG2 if picture is not None: IIB = "\x00\x01" + inttostring(pic_width, 2) +\ inttostring(pic_height, 2) + 6 * "\x00" length = 32 + len(picture) # 32 is the length of IIB + FIB FIB = inttostring(length, 4) + 16 * "\x00" FRH = "FAC" + "\x00" + "010" + "\x00" +\ inttostring(14 + length, 4) + inttostring(1, 2) picture = FRH + FIB + IIB + picture DG2 = pack([(0xA1, 8, "\x87\x02\x01\x01\x88\x02\x05\x01"), (0x5F2E, len(picture), picture)]) DG2 = pack([(0x02, 1, "\x01"), (0x7F60, len(DG2), DG2)]) DG2 = pack([(0x7F61, len(DG2), DG2)]) else: DG2 = "" df.append( TransparentStructureEF(parent=df, fid=0x0102, filedescriptor=0, data=DG2)) # EF.SOD df.append( TransparentStructureEF(parent=df, fid=0x010D, filedescriptor=0, data="")) mf.append(df) self.mf = mf self.sam = PassportSAM(self.mf)
def setup_readline(namespace_module=__main__): """ Install Jedi completer to :mod:`readline`. This function setups :mod:`readline` to use Jedi in Python interactive shell. If you want to use a custom ``PYTHONSTARTUP`` file (typically ``$HOME/.pythonrc.py``), you can add this piece of code:: try: from jedi.utils import setup_readline setup_readline() except ImportError: # Fallback to the stdlib readline completer if it is installed. # Taken from http://docs.python.org/2/library/rlcompleter.html print("Jedi is not installed, falling back to readline") try: import readline import rlcompleter readline.parse_and_bind("tab: complete") except ImportError: print("Readline is not installed either. No tab completion is enabled.") This will fallback to the readline completer if Jedi is not installed. The readline completer will only complete names in the global namespace, so for example:: ran<TAB> will complete to ``range`` with both Jedi and readline, but:: range(10).cou<TAB> will show complete to ``range(10).count`` only with Jedi. You'll also need to add ``export PYTHONSTARTUP=$HOME/.pythonrc.py`` to your shell profile (usually ``.bash_profile`` or ``.profile`` if you use bash). """ if READLINE_DEBUG: logging.basicConfig(filename='/tmp/jedi.log', filemode='a', level=logging.DEBUG) class JediRL(object): def complete(self, text, state): """ This complete stuff is pretty weird, a generator would make a lot more sense, but probably due to backwards compatibility this is still the way how it works. The only important part is stuff in the ``state == 0`` flow, everything else has been copied from the ``rlcompleter`` std. library module. """ if state == 0: sys.path.insert(0, os.getcwd()) # Calling python doesn't have a path, so add to sys.path. try: logging.debug("Start REPL completion: " + repr(text)) interpreter = Interpreter(text, [namespace_module.__dict__]) lines = split_lines(text) position = (len(lines), len(lines[-1])) name = get_on_completion_name(interpreter._module_node, lines, position) before = text[:len(text) - len(name)] completions = interpreter.completions() logging.debug("REPL completions: %s", completions) except: logging.error("REPL Completion error:\n" + traceback.format_exc()) raise finally: sys.path.pop(0) self.matches = [ before + c.name_with_symbols for c in completions ] try: return self.matches[state] except IndexError: return None try: # Need to import this one as well to make sure it's executed before # this code. This didn't use to be an issue until 3.3. Starting with # 3.4 this is different, it always overwrites the completer if it's not # already imported here. import rlcompleter import readline except ImportError: print("Jedi: Module readline not available.") else: readline.set_completer(JediRL().complete) readline.parse_and_bind("tab: complete") # jedi itself does the case matching readline.parse_and_bind("set completion-ignore-case on") # because it's easier to hit the tab just once readline.parse_and_bind("set show-all-if-unmodified") readline.parse_and_bind("set show-all-if-ambiguous on") # don't repeat all the things written in the readline all the time readline.parse_and_bind("set completion-prefix-display-length 2") # No delimiters, Jedi handles that. readline.set_completer_delims('')
def __init__(self, con): readline.set_completer_delims(' \t\n;') readline.set_history_length(100) readline.set_completer(self.complete) readline.parse_and_bind("tab: complete") self.con = con
import titus.inspector.parser as parser from titus.reader import jsonToAst from titus.genpy import PFAEngine from titus.errors import AvroException, SchemaParseException, PFAException CONFIG_DIRECTORY = "~/.pfa" CONFIG_DIRECTORY_EXISTS = True if not os.path.exists(os.path.expanduser(CONFIG_DIRECTORY)): if raw_input("Create {0} for configuration files? (Y/n): ".format(CONFIG_DIRECTORY)).upper().strip() in ("Y", ""): os.mkdir(os.path.expanduser(CONFIG_DIRECTORY)) else: CONFIG_DIRECTORY_EXISTS = False CONFIG_COMPLETER_DELIMS = " \t[],:=" readline.set_completer_delims(CONFIG_COMPLETER_DELIMS) readline.parse_and_bind("tab: complete") readline.parse_and_bind(r'"\eh": backward-kill-word') readline.parse_and_bind(r'"\ep": history-search-backward') readline.parse_and_bind(r'"\en": history-search-forward') class TabCompleter(object): """Handles tab-completion in pfainspector.""" def __init__(self, mode): """:type mode: titus.inspector.defs.Mode :param mode: the pfainspector mode in which this tab completer is active """ self.mode = mode
def start(self): # Logo. logo() # Setup shell auto-complete. def complete(text, state): # Try to autocomplete commands. cmds = [i for i in self.cmd.commands if i.startswith(text)] if state < len(cmds): return cmds[state] # Try to autocomplete modules. mods = [i for i in __modules__ if i.startswith(text)] if state < len(mods): return mods[state] # Then autocomplete paths. if text.startswith("~"): text = "{0}{1}".format(os.getenv("HOME"), text[1:]) return (glob.glob(text + '*') + [None])[state] # Auto-complete on tabs. readline.set_completer_delims(' \t\n;') readline.parse_and_bind('tab: complete') readline.set_completer(complete) # Save commands in history file. def save_history(path): readline.write_history_file(path) # If there is an history file, read from it and load the history # so that they can be loaded in the shell. # Now we are storing the history file in the local project folder history_path = os.path.join(__project__.path, 'history') if os.path.exists(history_path): readline.read_history_file(history_path) # Register the save history at program's exit. atexit.register(save_history, path=history_path) # Main loop. while self.active: # If there is an open session, we include the path to the opened # file in the shell prompt. # TODO: perhaps this block should be moved into the session so that # the generation of the prompt is done only when the session's # status changes. prefix = '' if __project__.name: prefix = bold(cyan(__project__.name)) + ' ' if __sessions__.is_set(): stored = '' filename = '' if __sessions__.current.file: filename = __sessions__.current.file.name if not Database().find( key='sha256', value=__sessions__.current.file.sha256): stored = magenta(' [not stored]', True) misp = '' if __sessions__.current.misp_event: misp = ' [MISP {}]'.format( __sessions__.current.misp_event.event_id) prompt = (prefix + cyan('viper ', True) + white(filename, True) + blue(misp, True) + stored + cyan(' > ', True)) # Otherwise display the basic prompt. else: prompt = prefix + cyan('viper > ', True) # Wait for input from the user. try: data = input(prompt).strip() except KeyboardInterrupt: print("") # Terminate on EOF. except EOFError: self.stop() print("") continue # Parse the input if the user provided any. else: # If there are recognized keywords, we replace them with # their respective value. data = self.keywords(data) # Skip if the input is empty. if not data: continue # Check for output redirection # If there is a > in the string, we assume the user wants to output to file. filename = False if '>' in data: data, filename = data.split('>') # If the input starts with an exclamation mark, we treat the # input as a bash command and execute it. # At this point the keywords should be replaced. if data.startswith('!'): os.system(data[1:]) continue # Try to split commands by ; so that you can sequence multiple # commands at once. # For example: # viper > find name *.pdf; open --last 1; pdf id # This will automatically search for all PDF files, open the first entry # and run the pdf module against it. split_commands = data.split(';') for split_command in split_commands: split_command = split_command.strip() if not split_command: continue # If it's an internal command, we parse the input and split it # between root command and arguments. root, args = self.parse(split_command) # Check if the command instructs to terminate. if root in ('exit', 'quit'): self.stop() continue try: # If the root command is part of the embedded commands list we # execute it. if root in self.cmd.commands: self.cmd.commands[root]['obj'](*args) print_output(self.cmd.output, filename) del (self.cmd.output[:]) # If the root command is part of loaded modules, we initialize # the module and execute it. elif root in __modules__: module = __modules__[root]['obj']() module.set_commandline(args) module.run() print_output(module.output, filename) if cfg.modules.store_output and __sessions__.is_set( ): try: Database().add_analysis( __sessions__.current.file.sha256, split_command, module.output) except: pass del (module.output[:]) else: print("Command not recognized.") except KeyboardInterrupt: pass except Exception as e: print_error( "The command {0} raised an exception:".format( bold(root))) traceback.print_exc()
def payload_selection_menu(self, showTitle=True): """ Menu to prompt the user for a custom shellcode string. Returns None if nothing is specified. """ # print out the main title to reset the interface if showTitle: evasion_helpers.title_screen() print(' [?] Generate or supply custom shellcode?\n') print(' %s - Ordnance %s' % (helpers.color('1'), helpers.color('(default)', yellow=True))) print(' %s - MSFVenom' % (helpers.color('2'))) print(' %s - custom shellcode string' % (helpers.color('3'))) print(' %s - file with shellcode (raw)\n' % (helpers.color('4'))) try: choice = self.required_options['SHELLCODE'][0].lower().strip() print(" [>] Please enter the number of your choice: %s" % (choice)) except: choice = input( " [>] Please enter the number of your choice: ").strip() if choice == '4': # instantiate our completer object for path completion comp = completer.PathCompleter() # we want to treat '/' as part of a word, so override the delimiters readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(comp.complete) # if the shellcode is specicified as a raw file filePath = input( " [>] Please enter the path to your raw shellcode file: ") try: with open(filePath, 'r') as shellcode_file: file_shellcode = shellcode_file.read() file_shellcode = file_shellcode.strip() except: print( helpers.color( " [!] WARNING: path not found, defaulting to msfvenom!", warning=True)) return None if len(file_shellcode) == 0: print( helpers.color( " [!] WARNING: no custom shellcode restrieved, defaulting to msfvenom!", warning=True)) return None # check if the shellcode was passed in as string-escaped form if file_shellcode[0:2] == "\\x" and file_shellcode[4:6] == "\\x": return file_shellcode else: # otherwise encode the raw data as a hex string hexString = binascii.hexlify(file_shellcode) file_shellcode = "\\x" + "\\x".join( [hexString[i:i + 2] for i in range(0, len(hexString), 2)]) return file_shellcode # remove the completer readline.set_completer(None) elif choice == '3' or choice == 'string': # if the shellcode is specified as a string cust_sc = input( " [>] Please enter custom shellcode (one line, no quotes, \\x00.. format): " ) if len(cust_sc) == 0: print( helpers.color( " [!] WARNING: no shellcode specified, defaulting to msfvenom!", warning=True)) return cust_sc elif choice == '' or choice == '1' or choice.lower( ) == 'veil-ordnance' or choice.lower() == 'ordnance': return 'ordnance' elif choice == '2' or choice.lower() == 'msf' or choice.lower( ) == 'metasploit' or choice.lower() == 'msfvenom': return None else: print( helpers.color( " [!] WARNING: Invalid option chosen, defaulting to Ordnance!", warning=True)) return 'ordnance'
# See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import cmd import shlex import random from datetime import datetime import json from termcolor import colored, cprint import sys import six try: import readline readline.set_completer_delims(" ,") except: pass from ..execute import ( RemoteExecutor, ) DEFAULT_COLOR_KEYWORDS = { "UP": "green", "DOWN": "red", "node": "blue", "pod": "blue", "ip": "yellow", "extIp": "yellow", }
def menu(self): """ Main interactive menu for shellcode selection. Utilizes Completer() to do tab completion on loaded metasploit payloads. """ selected_payload = None options = None showMessage = False if settings.TERMINAL_CLEAR != "false": showMessage = True # if no generation method has been selected yet if self.msfvenomCommand == "" and self.custom_shellcode == "": # show banner? if settings.TERMINAL_CLEAR != "false": showMessage = True # prompt for custom shellcode or msfvenom custom_shellcode = self.payload_selection_menu(showMessage) # if custom shellcode is specified, set it if custom_shellcode == "ordnance": # Start figuring out Ordnance stuff here self.invoke_ordnance = True elif custom_shellcode: self.custom_shellcode = custom_shellcode # else, if no custom shellcode is specified, prompt for metasploit else: # instantiate our completer object for tab completion of available payloads comp = completer.MSFCompleter(self.payload_tree) # we want to treat '/' as part of a word, so override the delimiters readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(comp.complete) # have the user select the payload while selected_payload is None: print( '\n [*] Press %s for windows/meterpreter/reverse_tcp' % helpers.color('[enter]', yellow=True)) print(' [*] Press %s to list available payloads' % helpers.color('[tab]', yellow=True)) try: selected_payload = self.required_options[ 'MSF_PAYLOAD'][0] print(' [>] Please enter metasploit payload: %s' % (selected_payload)) except: selected_payload = input( ' [>] Please enter metasploit payload: ').strip( ).lower() if selected_payload == "": # default to reverse_tcp for the payload selected_payload = "windows/meterpreter/reverse_tcp" try: parts = selected_payload.split("/") # walk down the selected parts of the payload tree to get to the options at the bottom options = self.payload_tree for part in parts: options = options[part] except KeyError: # make sure user entered a valid payload if 'PAYLOAD' in self.required_options: del self.required_options['PAYLOAD'] print( helpers.color( " [!] ERROR: Invalid payload specified!\n", warning=True)) selected_payload = None # remove the tab completer readline.set_completer(None) # set the internal payload to the one selected self.msfvenompayload = selected_payload # request a value for each required option for option in options: value = "" while value == "": ### VALIDATION ### # LHOST is a special case, so we can tab complete the local IP if option == "LHOST": try: value = self.required_options['LHOST'][0] print( ' [>] Enter value for \'LHOST\', [tab] for local IP: %s' % (value)) except: # set the completer to fill in the local IP readline.set_completer( completer.IPCompleter().complete) value = input( ' [>] Enter value for \'LHOST\', [tab] for local IP: ' ).strip() if '.' in value: hostParts = value.split(".") if len(hostParts) > 1: # if the last chunk is a number, assume it's an IP address if hostParts[-1].isdigit(): # do a IP validation check if not helpers.validate_ip(value): if 'LHOST' in self.required_options: self.required_options['LHOST'][ 0] = '' print( helpers.color( "\n [!] ERROR: Bad IP address specified.\n", warning=True)) value = "" # otherwise assume we've been passed a domain name else: if not helpers.validate_hostname( value): if 'LHOST' in self.required_options: self.required_options['LHOST'][ 0] = '' print( helpers.color( "\n [!] ERROR: Bad hostname specified.\n", warning=True)) value = "" # if we don't have at least one period in the hostname/IP else: if 'LHOST' in self.required_options: del self.required_options['LHOST'] print( helpers.color( "\n [!] ERROR: Bad IP address or hostname specified.\n", warning=True)) value = "" elif ':' in value: try: socket.inet_pton(socket.AF_INET6, value) except socket.error: if 'LHOST' in self.required_options: self.required_options['LHOST'][0] = '' print( helpers.color( "\n [!] ERROR: Bad IP address or hostname specified.\n", warning=True)) value = "" else: if 'LHOST' in self.required_options: self.required_options['LHOST'][0] = '' print( helpers.color( "\n [!] ERROR: Bad IP address or hostname specified.\n", warning=True)) value = "" elif option == "LPORT": try: value = self.required_options['LPORT'][0] print(' [>] Enter value for \'LPORT\': %s' % (value)) except: # set the completer to fill in the default MSF port (4444) readline.set_completer( completer.MSFPortCompleter().complete) value = input( ' [>] Enter value for \'LPORT\': ').strip( ) try: if int(value) <= 0 or int(value) >= 65535: print( helpers.color( " [!] ERROR: Bad port number specified.\n", warning=True)) if 'LPORT' in self.required_options: self.required_options['LPORT'][0] = '' value = "" except ValueError: print( helpers.color( " [!] ERROR: Bad port number specified.\n", warning=True)) if 'LPORT' in self.required_options: self.required_options['LPORT'][0] = '' value = "" else: value = input(' [>] Enter value for \'' + option + '\': ').strip() # append all the msfvenom options self.msfvenom_options.append(option + "=" + value) # allow the user to input any extra OPTION=value pairs extra_msf_options = list() while True: # clear out the tab completion readline.set_completer(completer.none().complete) selection = input( ' [>] Enter any extra msfvenom options (syntax: OPTION1=value1 or -OPTION2=value2): ' ).strip() if selection != "": num_extra_options = selection.split(' ') for xtra_opt in num_extra_options: if xtra_opt is not '': if "=" not in xtra_opt: print( helpers.color( " [!] Parameter not entered in correct syntax.\n", warning=True)) continue if "-" in xtra_opt.split('=')[0]: final_opt = xtra_opt.split( '=')[0] + " " + xtra_opt.split('=')[1] extra_msf_options.append(final_opt) else: final_opt = xtra_opt.split( '=')[0] + "=" + xtra_opt.split('=')[1] extra_msf_options.append(final_opt) else: break # grab any specified msfvenom options in the /etc/veil/settings.py file msfvenom_options = "" if hasattr(settings, "MSFVENOM_OPTIONS"): msfvenom_options = settings.MSFVENOM_OPTIONS # build out the msfvenom command self.msfvenomCommand = "msfvenom " + msfvenom_options + " -p " + selected_payload for option in self.msfvenom_options: self.msfvenomCommand += " " + option self.options.append(option) if len(extra_msf_options) != 0: self.msfvenomCommand += " " + " ".join(extra_msf_options) self.msfvenomCommand += " -f c | tr -d \'\"\' | tr -d \'\\n\'" return
def main(): import readline import stem.interpreter.arguments import stem.interpreter.autocomplete import stem.interpreter.commands try: args = stem.interpreter.arguments.parse(sys.argv[1:]) except ValueError as exc: print(exc) sys.exit(1) if args.print_help: print(stem.interpreter.arguments.get_help()) sys.exit() if args.disable_color or not sys.stdout.isatty(): global PROMPT stem.util.term.DISABLE_COLOR_SUPPORT = True PROMPT = '>>> ' # If the user isn't connecting to something in particular then offer to start # tor if it isn't running. if not (args.user_provided_port or args.user_provided_socket): is_tor_running = stem.util.system.is_running('tor') or stem.util.system.is_running('tor.real') if not is_tor_running: if args.tor_path == 'tor' and not stem.util.system.is_available('tor'): print(format(msg('msg.tor_unavailable'), *ERROR_OUTPUT)) sys.exit(1) else: if not args.run_cmd and not args.run_path: print(format(msg('msg.starting_tor'), *HEADER_OUTPUT)) control_port = '9051' if args.control_port == 'default' else str(args.control_port) try: stem.process.launch_tor_with_config( config = { 'SocksPort': '0', 'ControlPort': control_port, 'CookieAuthentication': '1', 'ExitPolicy': 'reject *:*', }, tor_cmd = args.tor_path, completion_percent = 5, take_ownership = True, ) except OSError as exc: print(format(msg('msg.unable_to_start_tor', error = exc), *ERROR_OUTPUT)) sys.exit(1) control_port = (args.control_address, args.control_port) control_socket = args.control_socket # If the user explicitely specified an endpoint then just try to connect to # that. if args.user_provided_socket and not args.user_provided_port: control_port = None elif args.user_provided_port and not args.user_provided_socket: control_socket = None controller = stem.connection.connect( control_port = control_port, control_socket = control_socket, password_prompt = True, ) if controller is None: sys.exit(1) with controller: autocompleter = stem.interpreter.autocomplete.Autocompleter(controller) readline.parse_and_bind('tab: complete') readline.set_completer(autocompleter.complete) readline.set_completer_delims('\n') interpreter = stem.interpreter.commands.ControlInterpreter(controller) showed_close_confirmation = False if args.run_cmd: if args.run_cmd.upper().startswith('SETEVENTS '): # TODO: we can use a lambda here when dropping python 2.x support, but # until then print's status as a keyword prevents it from being used in # lambdas def handle_event(event_message): print(format(str(event_message), *STANDARD_OUTPUT)) controller._handle_event = handle_event if sys.stdout.isatty(): events = args.run_cmd.upper().split(' ', 1)[1] print(format('Listening to %s events. Press any key to quit.\n' % events, *HEADER_BOLD_OUTPUT)) controller.msg(args.run_cmd) try: raw_input() except (KeyboardInterrupt, stem.SocketClosed) as exc: pass else: interpreter.run_command(args.run_cmd, print_response = True) elif args.run_path: try: for line in open(args.run_path).readlines(): interpreter.run_command(line.strip(), print_response = True) except IOError as exc: print(format(msg('msg.unable_to_read_file', path = args.run_path, error = exc), *ERROR_OUTPUT)) sys.exit(1) else: for line in msg('msg.startup_banner').splitlines(): line_format = HEADER_BOLD_OUTPUT if line.startswith(' ') else HEADER_OUTPUT print(format(line, *line_format)) print('') while True: try: prompt = '... ' if interpreter.is_multiline_context else PROMPT user_input = input(prompt) if stem.prereq.is_python_3() else raw_input(prompt) interpreter.run_command(user_input, print_response = True) except stem.SocketClosed as exc: if showed_close_confirmation: print(format('Unable to run tor commands. The control connection has been closed.', *ERROR_OUTPUT)) else: prompt = format("Tor's control port has closed. Do you want to continue this interpreter? (y/n) ", *HEADER_BOLD_OUTPUT) user_input = input(prompt) if stem.prereq.is_python_3() else raw_input(prompt) print('') # blank line if user_input.lower() in ('y', 'yes'): showed_close_confirmation = True else: break except (KeyboardInterrupt, EOFError, stem.SocketClosed) as exc: print('') # move cursor to the following line break
import os import readline import glob from builtins import input import numpy as np from spectrum import Spectrum from errors.spectrum_error import SpectrumError # this is so that input can autocomplete using the tab def complete(text, state): return (glob.glob(text + '*') + [None])[state] readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete) def loadTestImage(): image_name = "test/test_image.fits" try: spec = Spectrum(image_name) except SpectrumError as e: message = "{}\nLoad error".format(e) return message, None return "Load successful", spec
def readlineCompleteRead(self): readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") return raw_input()
def _autocomplete_dash_characters(self): # This changes the special characters, so we can autocomplete on the - character old_delims = readline.get_completer_delims() readline.set_completer_delims(old_delims.replace('-', ''))
## ret = ret + get_class_members(base) ## return ret readline.set_completer(Completer().complete) # peter added, so that it would not split words in the input line on a "(" import string delims = readline.get_completer_delims() #print "delims = %s" % delims delimList = list(delims) if '(' in delimList: delimList.remove('(') if 1: delimList.remove('[') delimList.remove(']') #print delimList readline.set_completer_delims(string.join(delimList, '')) # make the tab work for completion try: from .Var import var #print "var.readlineUsesEditline is %s" % var.readlineUsesEditline if var.readlineUsesEditline: # For Mac OS 10.5, which uses editline, not readline, and has a different syntax. readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") except ImportError: readline.parse_and_bind("tab: complete")
def main(): readline.set_completer_delims(' \t\n;') readline.parse_and_bind('tab: complete') readline.set_completer(complete_path) print('Welcome to Cortex: a deep learning toolbox for ' 'neuroimaging') print( 'Cortex requires that you enter some paths for ' 'default dataset and output directories. These ' 'can be changed at any time and are customizable ' 'via the ~/.cortexrc file.') try: path_dict = get_paths() except ValueError: path_dict = dict() if '$data' in path_dict: data_path = raw_input('Default data path: [%s] ' % path_dict['$data']) or path_dict['$data'] else: data_path = raw_input('Default data path: ') data_path = path.expanduser(data_path) if not path.isdir(data_path): raise ValueError('path %s does not exist. Please create it.' % data_path) if '$outs' in path_dict: out_path = raw_input('Default output path: [%s] ' % path_dict['$outs']) or path_dict['$outs'] else: out_path = raw_input('Default output path: ') out_path = path.expanduser(data_path) if not path.isdir(out_path): raise ValueError('path %s does not exist. Please create it.' % out_path) write_path_conf(data_path, out_path) print( 'Cortex demos require additional data that is not necessary for ' 'general use of the Cortex as a package.' 'This includes MNIST, Caltech Silhoettes, and some UCI dataset ' 'samples.') answer = query_yes_no('Download basic dataset? ') if answer: try: fetch_basic_data() except urllib2.HTTPError: print 'Error: basic dataset not found.' print( 'Cortex also requires neuroimaging data for the neuroimaging data ' 'for the neuroimaging demos. These are large and can be skipped.') answer = query_yes_no('Download neuroimaging dataset? ') if answer: try: fetch_neuroimaging_data() except urllib2.HTTPError: print 'Error: neuroimaging dataset not found.'
def commandloop(implant_id, user): while (True): try: implant_id_orig = implant_id t = tabCompleter() t.createListCompleter(COMMANDS) readline.set_completer_delims('\t') readline.parse_and_bind("tab: complete") readline.set_completer(t.listCompleter) if ("-" in implant_id) or ("all" in implant_id) or ("," in implant_id): print(Colours.GREEN) command = input("%s> " % (implant_id)) else: hostname = get_hostdetails(implant_id) if not hostname: startup( user, "Unrecognised implant id or command: %s" % implant_id) if hostname[15] == 'Python': t.createListCompleter(UXCOMMANDS) readline.set_completer_delims('\t') readline.parse_and_bind("tab: complete") readline.set_completer(t.listCompleter) if hostname[15] == 'C#': t.createListCompleter(SHARPCOMMANDS) readline.set_completer_delims('\t') readline.parse_and_bind("tab: complete") readline.set_completer(t.listCompleter) print(Colours.GREEN) print("%s\\%s @ %s (PID:%s)" % (hostname[11], hostname[2], hostname[3], hostname[8])) command = input("%s> " % (implant_id)) # if "all" run through all implants get_implants() if implant_id == "all": if command == "back": startup(user) implant_split = get_implants() if implant_split: for implant_id in implant_split: runcommand(command, implant_id[1]) # if "seperated list" against single uri elif "," in implant_id: implant_split = implant_id.split(",") for implant_id in implant_split: implant_id = get_randomuri(implant_id) runcommand(command, implant_id) # if "range" against single uri elif "-" in implant_id: implant_split = implant_id.split("-") for implant_id in range(int(implant_split[0]), int(implant_split[1]) + 1): try: implant_id = get_randomuri(implant_id) runcommand(command, implant_id) except Exception: print("Unknown ImplantID") # else run against single uri else: implant_id = get_randomuri(implant_id) runcommand(command, implant_id) # then run back around commandloop( implant_id_orig, user ) # is this required for a while loop? looks like it would lead to a stackoverflow anyway? except Exception as e: print(Colours.RED) print( "Error running against the selected implant ID, ensure you have typed the correct information" ) print(Colours.END) traceback.print_exc() print("Error: %s" % e) time.sleep(1) startup(user, user)
self.matches = [] for i in files: curPath = os.path.join(dirName, i) if os.path.isdir(curPath): self.matches.append(curPath + os.sep) else: self.matches.append(curPath) try: return self.matches[state] except: return None completer = Completer() readline.set_completer(completer.complete) readline.parse_and_bind("tab: complete") readline.set_completer_delims('\t\n`!@#$%^&*)=+[{]}\\|;:,<>?') binutils = (raw_input('Please specify the binutils archive: ')).replace('\n', '').strip() while ' ' in binutils: print 'Whitespace in path ' + binutils + '.' binutils = (raw_input('Please specify a valid binutils archive: ')).replace('\n', '').strip() while not os.path.exists(binutils): print 'Path ' + binutils + ' does not exist.' binutils = (raw_input('Please specify the binutils archive: ')).replace('\n', '').strip() gcc = (raw_input('Please specify the gcc archive: ')).replace('\n', '').strip() while ' ' in gcc: print 'Whitespace in path ' + gcc + '.' gcc = (raw_input('Please specify a valid gcc archive: ')).replace('\n', '').strip() while not os.path.exists(gcc): print 'Path ' + gcc + ' does not exist.'
def init_completer(self): readline.set_pre_input_hook(self.pre_input_hook) readline.set_completer_delims(" \t")
def checkPACKAGE(package, FiGS_Version): if package.__version__ < FiGS_Version: print ">The required version for " + str( package.__name__) + " is " + str(FiGS_Version) print ">Yours is " + str(package.__version__) + "\n" sys.exit() checkPACKAGE(np, "1.15.0") checkPACKAGE(mpl, "2.2.3") checkPACKAGE(astropy, "1.1.2") #################################### OPEN FITS ############################# readline.parse_and_bind('tab: complete') readline.set_completer_delims(' ') filename = raw_input( ">Input your FITS file (do not forget to include the extension!) \n") while os.path.isfile(filename) != True: print ">The file does not exist." filename = raw_input(">Retry \n") #filename = user_input #'hst_08301_41_wfpc2_f606w_wf_drz.fits' alpha = 1e-2 beta = 5.5e-3 gamma = 2.5e-2 z = float(raw_input(">Input the redshift of the object in the fits\n"))
def tool_main_menu(self): # This is the main function where everything is called from # Iterate over payloads and find the user selected payload module evasion_main_command = '' show_evasion_menu = True while evasion_main_command == '': # set out tab completion for the appropriate modules on each run # as other modules sometimes reset this comp = completer.MainMenuCompleter(self.evasion_main_menu_commands, self.active_payloads) readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(comp.complete) if show_evasion_menu: evasion_helpers.title_screen() print("Veil-Evasion Menu") print("\n\t" + helpers.color(len(self.active_payloads)) + " payloads loaded\n") print("Available Commands:\n") for command in sorted(self.evasion_main_menu_commands.keys()): print("\t" + helpers.color(command) + '\t\t\t' + self.evasion_main_menu_commands[command]) print() show_evasion_menu = True evasion_main_command = input('Veil-Evasion command: ').strip() if evasion_main_command.lower() == "back": evasion_main_command = '' break elif evasion_main_command.lower() == "checkvt": self.check_vt() evasion_main_command = '' elif evasion_main_command.lower() == "clean": self.clean_artifacts() evasion_main_command = '' elif evasion_main_command.lower() == "exit": sys.exit(0) elif evasion_main_command.lower().startswith('info'): if len(evasion_main_command.split()) == 2: payload_selected = evasion_main_command.split()[1] selected_payload_module = self.return_payload_object(payload_selected) if not selected_payload_module: print() print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) print() evasion_main_command = '' show_evasion_menu = False else: self.print_options_screen(selected_payload_module) evasion_main_command = '' show_evasion_menu = False else: print() print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) print() evasion_main_command = '' show_evasion_menu = False elif evasion_main_command.lower().startswith('list'): evasion_helpers.title_screen() self.list_loaded_payloads() show_evasion_menu = False print() evasion_main_command = '' elif evasion_main_command.lower().startswith('use'): if len(evasion_main_command.split()) == 2: payload_selected = evasion_main_command.split()[1] selected_payload_module = self.return_payload_object(payload_selected) if not selected_payload_module: print() print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) print() evasion_main_command = '' show_evasion_menu = False else: self.use_payload(selected_payload_module) evasion_main_command = '' show_evasion_menu = True else: print() print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) print(helpers.color("[*] Ex: use 2 or use lua/shellcode_inject/flat.py", warning=True)) print() evasion_main_command = '' show_evasion_menu = False else: evasion_main_command = '' return
def startup(user, printhelp=""): try: if os.name == 'nt': os.system('cls') else: os.system('clear') except Exception: print("cls") print(chr(27) + "[2J") print(Colours.GREEN) print(logopic) try: if user is not None: print("User: "******"%s%s" % (user, Colours.END)) print("") ii = get_implants() if ii: for i in ii: ID = i[0] LastSeen = i[7] Hostname = i[3] Domain = i[11] DomainUser = i[2] Arch = i[10] PID = i[8] Pivot = i[15] Sleep = i[13].strip() Label = i[16] pivot_original = Pivot if pivot_original.startswith("PS"): Pivot = "PS" elif pivot_original.startswith("C#"): Pivot = "C#" elif pivot_original.startswith("Python"): Pivot = "PY" if "Daisy" in pivot_original: Pivot = Pivot + ";D" if "Proxy" in pivot_original: Pivot = Pivot + ";P" from datetime import datetime, timedelta LastSeenTime = datetime.strptime(LastSeen, "%d/%m/%Y %H:%M:%S") now = datetime.now() if (Sleep.endswith('s')): sleep_int = int(Sleep[:-1]) elif (Sleep.endswith('m')): sleep_int = int(Sleep[:-1]) * 60 elif (Sleep.endswith('h')): sleep_int = int(Sleep[:-1]) * 60 * 60 else: print(Colours.RED) print("Incorrect sleep format: %s" % Sleep) print(Colours.END) continue nowMinus3Beacons = now - timedelta(seconds=(sleep_int * 3)) nowMinus10Beacons = now - timedelta(seconds=(sleep_int * 10)) sID = "[" + str(ID) + "]" if not Label: sLabel = "" else: sLabel = "[" + Label + "]" if nowMinus10Beacons > LastSeenTime: print(Colours.RED + "%s%s: Seen:%s | PID:%s | %s | %s\\%s @ %s (%s) %s" % (sID.ljust(4), sLabel, LastSeen, PID.ljust(5), Sleep, Domain, DomainUser, Hostname, Arch, Pivot)) elif nowMinus3Beacons > LastSeenTime: print(Colours.YELLOW + "%s%s: Seen:%s | PID:%s | %s | %s\\%s @ %s (%s) %s" % (sID.ljust(4), sLabel, LastSeen, PID.ljust(5), Sleep, Domain, DomainUser, Hostname, Arch, Pivot)) else: print(Colours.GREEN + "%s%s: Seen:%s | PID:%s | %s | %s\\%s @ %s (%s) %s" % (sID.ljust(4), sLabel, LastSeen, PID.ljust(5), Sleep, Domain, DomainUser, Hostname, Arch, Pivot)) else: from datetime import datetime, timedelta now = datetime.now() print(Colours.RED + "No Implants as of: %s" % now.strftime("%d/%m/%Y %H:%M:%S")) print(Colours.END + "") if printhelp: print(printhelp) t = tabCompleter() t.createListCompleter(PRECOMMANDS) readline.set_completer_delims('\t') readline.parse_and_bind("tab: complete") readline.set_completer(t.listCompleter) history = get_history_dict() if history: for command in history: try: readline.add_history(command[1]) except Exception: pass command = input( "Select ImplantID or ALL or Comma Separated List (Enter to refresh):: " ) print("") if command: try: last = get_lastcommand() if last: if last != command: new_commandhistory(command) else: new_commandhistory(command) except Exception: pass command = command.strip() if (command == "") or (command == "back") or (command == "clear"): startup(user) if command.startswith("output-to-html"): generate_table("Tasks") generate_table("C2Server") generate_table("Creds") generate_table("Implants") graphviz() time.sleep(1) startup(user) if command.startswith("show-urls") or command.startswith("list-urls"): urls = get_c2urls() urlformatted = "RandomID URL HostHeader ProxyURL ProxyUsername ProxyPassword CredentialExpiry\n" for i in urls: urlformatted += "%s %s %s %s %s %s %s %s \n" % ( i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]) startup(user, urlformatted) if command.startswith("add-autorun"): if command == "add-autorun": startup(user, "Please specify a module to autorun") autorun = command.replace("add-autorun ", "") autorun = autorun.replace("add-autorun", "") add_autorun(autorun) startup(user, "add-autorun: %s\r\n" % autorun) if command.startswith("list-autorun"): autoruns = get_autorun() startup(user, autoruns) if command.startswith("del-autorun"): autorun = command.replace("del-autorun ", "") del_autorun(autorun) startup(user, "deleted autorun\r\n") if command.startswith("nuke-autorun"): del_autoruns() startup(user, "nuked autoruns\r\n") if (command == "automigrate-frompowershell") or (command == "am"): startup( user, "automigrate not currently implemented for the Python version of PoshC2\r\n" ) if command.startswith("show-serverinfo"): i = get_c2server_all() detailsformatted = "\nHostnameIP: %s\nEncKey: %s\nDomainFrontHeader: %s\nDefaultSleep: %s\nKillDate: %s\nHTTPResponse: %s\nFolderPath: %s\nServerPort: %s\nQuickCommand: %s\nDownloadURI: %s\nDefaultProxyURL: %s\nDefaultProxyUser: %s\nDefaultProxyPass: %s\nEnableSounds: %s\nAPIKEY: %s\nMobileNumber: %s\nURLS: %s\nSocksURLS: %s\nInsecure: %s\nUserAgent: %s\nReferer: %s\nAPIToken: %s\nAPIUser: %s\nEnableNotifications: %s\n" % ( i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9], i[10], i[11], i[12], i[13], i[14], i[15], i[16], i[17], i[18], i[19], i[20], i[21], i[22], i[23], i[24]) startup(user, detailsformatted) if command.startswith("turnoff-notifications"): update_item("EnableNotifications", "C2Server", "No") startup(user, "Turned off notifications on new implant") if command.startswith("turnon-notifications"): update_item("EnableNotifications", "C2Server", "Yes") startup(user, "Turned on notifications on new implant") if command.startswith("set-clockworksmsapikey"): cmd = command.replace("set-clockworksmsapikey ", "") cmd = cmd.replace("set-clockworksmsapikey", "") update_item("MobileNumber", "C2Server", cmd) startup(user, "Updated set-clockworksmsapikey: %s\r\n" % cmd) if command.startswith("set-clockworksmsnumber"): cmd = command.replace("set-clockworksmsnumber ", "") cmd = cmd.replace("set-clockworksmsnumber", "") update_item("APIKEY", "C2Server", cmd) startup( user, "Updated set-clockworksmsnumber (Restart C2 Server): %s\r\n" % cmd) if command.startswith("set-killdate"): cmd = command.replace("set-killdate ", "") cmd = cmd.replace("set-killdate", "") update_item("KillDate", "C2Server", cmd) startup( user, "Updated KillDate (Remember to generate new payloads and get new implants): %s\r\n" % cmd) if command.startswith("set-defaultbeacon"): new_sleep = command.replace("set-defaultbeacon ", "") new_sleep = new_sleep.replace("set-defaultbeacon", "") if not validate_sleep_time(new_sleep): print(Colours.RED) print( "Invalid sleep command, please specify a time such as 50s, 10m or 1h" ) print(Colours.GREEN) startup(user) else: update_item("DefaultSleep", "C2Server", new_sleep) startup( user, "Updated set-defaultbeacon (Restart C2 Server): %s\r\n" % new_sleep) if command.startswith("opsec"): implants = get_implants_all() comtasks = get_tasks() hosts = "" uploads = "" urls = "" users = "" for i in implants: if i[3] not in hosts: hosts += "%s \n" % i[3] if i[9] not in urls: urls += "%s \n" % i[9] for t in comtasks: hostname = get_implantdetails(t[1]) command = t[2].lower() output = t[3].lower() if hostname[2] not in users: users += "%s\\%s @ %s\n" % (hostname[11], hostname[2], hostname[3]) if "uploading file" in command: uploadedfile = command uploadedfile = uploadedfile.partition( "uploading file: ")[2].strip() filehash = uploadedfile.partition( " with md5sum:")[2].strip() uploadedfile = uploadedfile.partition( " with md5sum:")[0].strip() uploadedfile = uploadedfile.strip('"') uploads += "%s\t%s\t%s\n" % (hostname[3], filehash, uploadedfile) if "installing persistence" in output: implant_details = get_implantdetails(t[2]) line = command.replace('\n', '') line = line.replace('\r', '') filenameuploaded = line.rstrip().split(":", 1)[1] uploads += "%s %s \n" % (implant_details[3], filenameuploaded) if "written scf file" in output: implant_details = get_implantdetails(t[2]) uploads += "%s %s\n" % (implant_details[3], output[output.indexof(':'):]) creds, hashes = parse_creds(get_creds()) startup( user, "Users Compromised: \n%s\nHosts Compromised: \n%s\nURLs: \n%s\nFiles Uploaded: \n%s\nCredentials Compromised: \n%s\nHashes Compromised: \n%s" % (users, hosts, urls, uploads, creds, hashes)) if command.startswith("listmodules"): mods = "" for modname in os.listdir("%s/Modules/" % POSHDIR): mods += "%s\r\n" % modname startup(user, mods) if command == "creds": creds, hashes = parse_creds(get_creds()) startup( user, "Credentials Compromised: \n%s\nHashes Compromised: \n%s" % (creds, hashes)) if command.startswith("creds ") and "-add " in command: p = re.compile(r"-domain=([^\s]*)") domain = re.search(p, command) if domain: domain = domain.group(1) p = re.compile(r"-username=([^\s]*)") username = re.search(p, command) if username: username = username.group(1) p = re.compile(r"-password=([^\s]*)") password = re.search(p, command) if password: password = password.group(1) p = re.compile(r"-hash=([^\s]*)") hash = re.search(p, command) if hash: hash = hash.group(1) if not domain or not username: startup(user, "Please specify a domain and username") if password and hash: startup(user, "Please specify a password or a hash, but not both") if not password and not hash: startup(user, "Please specify either a password or a hash") insert_cred(domain, username, password, hash) startup(user, "Credential added successfully") if command.startswith("creds ") and "-search " in command: username = command.replace("creds ", "") username = username.replace("-search ", "") username = username.strip() creds, hashes = parse_creds(get_creds_for_user(username)) startup( user, "Credentials Compromised: \n%s\nHashes Compromised: \n%s" % (creds, hashes)) if (command == "pwnself") or (command == "p"): subprocess.Popen( ["python", "%s%s" % (PayloadsDirectory, "py_dropper.py")]) startup(user) if (command == "tasks") or (command == "tasks "): alltasks = "" tasks = get_newtasks_all() if tasks is None: startup(user, "No tasks queued!\r\n") else: for task in tasks: imname = get_implantdetails(task[1]) alltasks += "(%s) %s\r\n" % ("%s\\%s" % (imname[11], imname[2]), task[2]) startup(user, "Queued tasks:\r\n\r\n%s" % alltasks) if (command == "cleartasks") or (command == "cleartasks "): drop_newtasks() startup(user, "Empty tasks queue\r\n") if command.startswith("quit"): ri = input("Are you sure you want to quit? (Y/n) ") if ri.lower() == "n": startup(user) if ri == "": sys.exit(0) if ri.lower() == "y": sys.exit(0) if command.startswith("createdaisypayload"): createdaisypayload(user, startup) if command.startswith("createproxypayload"): createproxypayload(user, startup) if command.startswith("createnewpayload"): createnewpayload(user, startup) if (command == "?") or (command == "help"): startup(user, pre_help) if (command == "history") or command == "history ": startup(user, get_history()) if command.startswith("use "): command = command.replace("use ", "") params = re.compile("use ", re.IGNORECASE) command = params.sub("", command) commandloop(command, user) except Exception as e: if 'unable to open database file' in str(e): startup(user) else: traceback.print_exc() print("Error: %s" % e) print("Currently no valid implants: sleeping for 10 seconds") time.sleep(10) startup(user)
def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. """ self.preloop() if self.use_rawinput and self.completekey: try: readline.read_history_file(self.conf['history_file']) readline.set_history_length(self.conf['history_size']) except IOError: # if history file does not exist try: open(self.conf['history_file'], 'w').close() readline.read_history_file(self.conf['history_file']) except IOError: pass readline.set_completer_delims( readline.get_completer_delims().replace('-', '')) self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey + ": complete") try: if self.intro and isinstance(self.intro, str): self.stdout.write("%s\n" % self.intro) if self.conf['login_script']: utils.exec_cmd(self.conf['login_script']) stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: if self.use_rawinput: try: # raw_input renamed as input in py3 try: line = raw_input(self.conf['promptprint']) except NameError: line = input(self.conf['promptprint']) except EOFError: line = 'EOF' except KeyboardInterrupt: self.stdout.write('\n') line = '' else: self.stdout.write(self.conf['promptprint']) self.stdout.flush() line = self.stdin.readline() if not len(line): line = 'EOF' else: # chop \n line = line[:-1] line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() finally: if self.use_rawinput and self.completekey: try: readline.set_completer_delims( readline.get_completer_delims().replace('-', '')) readline.set_completer(self.old_completer) except ImportError: pass try: readline.write_history_file(self.conf['history_file']) except IOError: self.log.error('WARN: couldn\'t write history ' 'to file %s\n' % self.conf['history_file'])
def use_payload(self, selected_payload): # Tab completion, thanks Will :) comp = completer.PayloadCompleter(self.payload_option_commands, selected_payload) readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(comp.complete) self.display_payload_options(selected_payload) payload_options_cmd = "" evasion_helpers.print_dict_message(self.payload_option_commands, show_title=False) while True: payload_options_cmd = input("\n[" + selected_payload.path + ">>] ").strip() if payload_options_cmd.lower() == "back" or payload_options_cmd.lower() == "main": payload_options_cmd = "" break elif payload_options_cmd.lower() == "generate": # Checking for Ruby specific payloads because of dumbass sleep check if selected_payload.language == 'ruby' and selected_payload.required_options["SLEEP"][0] != "X" and selected_payload.required_options["USERNAME"][0] == "X" and selected_payload.required_options["DOMAIN"][0] == "X" and selected_payload.required_options["HOSTNAME"][0] == "X": print(helpers.color("[*] If using SLEEP check with Ruby, you must also provide an additional check (like HOSTNAME)!", warning=True)) payload_options_cmd = "" else: selected_payload.generate() if not outfile.compiler(selected_payload): payload_options_cmd = "" else: payload_options_cmd = "" break elif payload_options_cmd.lower() == "exit": sys.exit(0) elif payload_options_cmd.lower() == "help" or payload_options_cmd.lower() == "options": self.print_options_screen(selected_payload) evasion_helpers.print_dict_message(self.payload_option_commands, show_title=False) payload_options_cmd = "" elif payload_options_cmd.lower().startswith("set"): if len(payload_options_cmd.split()) == 3: set_command, key, value = payload_options_cmd.split() # Make sure it is uppercase key = key.upper() if key in selected_payload.required_options: # Validate LHOST value if key is "LHOST": if helpers.validate_ip(value): selected_payload.required_options[key][0] = value else: print() print(helpers.color("[*] Error: You did not provide a valid IP!", warning=True)) print() payload_options_cmd = '' # Validate LPORT elif key is "LPORT": if helpers.validate_port(value): selected_payload.required_options[key][0] = value else: print() print(helpers.color("[*] Error: You did not provide a valid port number!", warning=True)) print() payload_options_cmd = '' else: # Set other options selected_payload.required_options[key][0] = value else: print() print(helpers.color("[*] Error: You did not provide a valid option!", warning=True)) print(helpers.color("[*] Ex: set LHOST 8.8.8.8", warning=True)) print() else: print() print(helpers.color("[*] Error: You did not provide a valid amount of arguments!", warning=True)) print(helpers.color("[*] Ex: set DOMAIN christest.com", warning=True)) print() payload_options_cmd = '' else: # Not a real command evasion_helpers.print_dict_message(self.payload_option_commands) payload_options_cmd = "" return
def interactive(parser, SLING_EXT=['py', 'R', 'ipynb']): slings = None import readline from .tab_completer import tabCompleter tabber = tabCompleter() args = parser.parse_args() args.sling = args.code args.stone = args.func args.stone_args = args.args readline.set_completer_delims('\t') if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") arg2help = dict([(x.dest, x.help) for x in parser.__dict__['_actions']]) opener_printed = False def print_opener(): print(SLINGSHOT) longest_line = max( len(line.rstrip()) for line in SLINGSHOT.split('\n')) HR = '\n' + '-' * longest_line + '\n' #print "### SLINGSHOT v0.1 ###" print( "## SLINGSHOT v0.1: interactive mode (see \"slingshot --help\" for more)" ) #print parser.format_help() opener_printed = True try: functions_str = '' if not args.llp_method: # SLING path_slings = CONFIG.get('PATH_SLINGS', '') SLING_EXT = CONFIG.get('SLING_EXT', '') if path_slings and os.path.exists(path_slings) and os.path.isdir( path_slings): slings = sorted([ fn for fn in os.listdir(path_slings) if fn.split('.')[-1] in SLING_EXT ]) #sling_str=' '.join(['(%s) %s' % (si+1, sl) for si,sl in enumerate(slings)]) sling_str = ' ' + '\n '.join( ['(%s) %s' % (si + 1, sl) for si, sl in enumerate(slings)]) while not args.sling: readline.set_completer(tabber.pathCompleter) if not opener_printed: print_opener() print('\n>> CODE ("Sling"): ' + arg2help['code']) if path_slings and slings: print( ' [numerical shortcuts for slings found in\n [{dir}]\n {slings}' .format(dir=path_slings, slings=sling_str)) sling = input('>> ').strip() if sling.isdigit() and 0 <= int(sling) - 1 < len(slings): args.sling = os.path.join(path_slings, slings[int(sling) - 1]) elif not os.path.exists(sling): print("!! filename does not exist") elif not sling.split('.')[-1] in SLING_EXT: print( "!! filename does not end in one of the acceptable file extensions [%s]" % ', '.join(SLING_EXT)) else: args.sling = sling # STONE longest_line = max( len(line.rstrip()) for line in SLINGSHOT.split('\n')) HR = '\n' + '-' * longest_line + '\n' print(HR) if args.sling.endswith('.py'): sling = imp.load_source('sling', args.sling) # functions = sling.STONES if hasattr(sling,'STONES') and sling.STONES else sorted([x for x,y in inspect.getmembers(sling, inspect.isfunction)]) # functions_str=' '.join(['(%s) %s' % (si+1, sl) for si,sl in enumerate(functions)]) # tabber.createListCompleter(functions) elif args.sling.endswith('.ipynb'): import nbimporter nbimporter.options['only_defs'] = CONFIG.get( 'NBIMPORTER_ONLY_DEFS', False) ppath, pfn = os.path.split(args.sling) pname, pext = os.path.splitext(pfn) NBL = nbimporter.NotebookLoader(path=[ppath]) sling = NBL.load_module(pname) else: sling = None functions_str = '' if sling: functions = sling.STONES if hasattr( sling, 'STONES') and sling.STONES else sorted([ x for x, y in inspect.getmembers( sling, inspect.isfunction) ]) functions_str = ' '.join([ '(%s) %s' % (si + 1, sl) for si, sl in enumerate(functions) ]) tabber.createListCompleter(functions) while not args.stone: #prompt='\n>> STONE: {help}\noptions: {opts}\n>>'.format(help=arg2help['stone'], opts=', '.join(functions)) #prompt='\n>> STONE: {help}\n>>'.format(help=arg2help['stone']) print('>> FUNC ("Stone"): ' + arg2help['func']) #print ' [options]: '+functions_str if functions_str: readline.set_completer(tabber.listCompleter) print(' ' + functions_str) stone = input('>> ').strip() if stone.isdigit() and 0 <= int(stone) - 1 < len(functions): args.stone = functions[int(stone) - 1] elif functions_str and not stone in functions: print("!! function not in file") else: args.stone = stone # PATH if not args.llp_corpus: print(HR) num2cname = {} try: import llp #from llp.corpus import load_manifest import pandas as pd #print('>> CORPUS: Type the number or name of an LLP corpus') print( '[LLP Corpus Library] (showing corpora with txt or xml folders installed)' ) #print() cnum = 0 for ci, (corpus, cdx) in enumerate( sorted(llp.corpus.load_manifest().items())): #for ci,(corpus,cdx) in enumerate(sorted(load_manifest().items())): #print(ci,corpus,cdx['path_txt']) #if not os.path.exists(cdx['path_txt']) and not os.path.exists(cdx['path_xml']): continue cnum += 1 num2cname[cnum] = corpus print('\t({num}) {name} ({desc})'.format( num=str(cnum), desc=cdx['desc'], name=cdx['name'])) #.zfill(2).replace('0','') #pd.options.display.max_colwidth = 100 #print(pd.DataFrame(llp.corpus.load_manifest()).T[['desc']]) print() """llp_input = input('>> ').strip() if llp_input.strip().isdigit(): cnum=int(llp_input.strip()) if cnum in num2cname: cname=num2cname[cnum] if corpus: args.llp_corpus=cname else: #corpus=llp.load_corpus(llp_input) #if corpus: args.llp_corpus=corpus args.llp_corpus=llp_input.strip()""" except ImportError as e: print('!!', e) #import sys #print(sys.path) pass #print(HR) opener = '>> CORPUS/PATH: ' opener_space = ' ' * len(opener) pathlists_str = '' while not (args.path or args.llp_corpus): readline.set_completer(tabber.pathCompleter) print(opener+'Please enter either ...\n'\ ' * a number to refer to an LLP corpus above\n' \ ' * a path to a folder, to find all files in that folder with a certain extension\n'\ ' * a path to a file, each line of which is the absolute path to another text file\n') path = input('>> ').strip() if path.isdigit(): cnum = int(path.strip()) if cnum in num2cname: cname = num2cname[cnum] if corpus: args.llp_corpus = cname elif not os.path.exists(path): print("!! filename or directory does not exist") elif os.path.isdir(path): args.ext = input('\n>> EXT: ' + arg2help['ext'] + '\n>> ').strip() args.path = path elif is_csv(path): args.path = path args.pathkey = input('\n>> COLUMN: ' + arg2help['pathkey'] + '\n>> ').strip() args.pathprefix = input('\n>> PREFIX: ' + arg2help['pathkey'] + '\n>> ').strip() args.pathsuffix = input('\n>> SUFFIX: ' + arg2help['pathkey'] + '\n>> ').strip() else: args.path = path if opener_printed: longest_line = max( len(line.rstrip()) for line in SLINGSHOT.split('\n')) HR = '\n' + '-' * longest_line + '\n' #print(HR) print('OPTIONAL SECTION') module = '.'.join(os.path.basename(args.sling).split('.')[:-1]) #default_savedir='/'.join(['results_slingshot',module,args.stone,now()]) default_savedir = '/'.join([ 'data_slingshot', args.stone + '_' + (args.llp_corpus if args.llp_corpus else os.path.basename(args.path)) ]) #args.nosave = input('\n>> SAVE: Save results? [Y]\n>> (Y/N) ').strip().lower()=='n' args.nosave = False if not args.nosave: args.savedir = iter_filename( input('\n>> SAVEDIR: Directory to store results in [%s]' % default_savedir + '\n>> ').strip()) #args.cache = input('\n>> CACHE: Cache partial results? [Y]\n>> (Y/N) ').strip().lower()=='y' args.cache = True #mfw = input('\n>> MFW: %s' % arg2help['mfw'] + '\n>> ').strip() mfw = None args.mfw = mfw if mfw else parser.get_default('mfw') #args.quiet = input('\n>> QUIET: %s? [N]\n>> (Y/N) ' % arg2help['quiet']).strip().lower()=='y' args.quiet = False args.limit = input('\n>> LIMIT: ' + arg2help['limit'] + ' [None]\n>> ').strip() args.sbatch = input( '\n>> SBATCH: Add to the SLURM/Sherlock process queue via sbatch? [N]\n>> (Y/N) ' ).strip().lower() == 'y' args.parallel = input('\n>> PARALLEL: ' + arg2help['parallel'] + ' [4]\n>> ').strip() if args.sbatch: hours = input('\n>> HOURS: ' + arg2help['hours'] + ' [1]\n>> ').strip() hours = ''.join([x for x in hours if x.isdigit()]) args.hours = parser.get_default('hours') if not hours else hours mem = input('\n>> MEMORY: ' + arg2help['mem'] + ' [2G]\n>> ').strip() args.mem = parser.get_default('mem') if not mem else mem else: #args.debug = input('\n>> DEBUG: %s? [N]\n>> (Y/N) ' % arg2help['debug']).strip().lower()=='y' args.debug = False print() except (KeyboardInterrupt, EOFError) as e: print('\n>> goodbye') exit() return args
def _setup_completer(self) -> None: readline.set_completer(self._complete) readline.set_completer_delims(" \t\n;") readline.parse_and_bind( "bind ^I rl_complete" if is_libedit() else "tab: complete")
def __init__(self, commands): readline.set_history_length(self.historysize) readline.parse_and_bind("tab: complete") readline.set_completer_delims(" \t\r\n") readline.set_completer(self.complete) self.commands = commands
def interactive(): t = tabCompleter() singluser = "" if args.interactive is True: print colors.white + "\n\nWelcome to interactive mode!\n\n" + colors.normal print colors.red + "WARNING:" + colors.white + " Leaving an option blank will leave it empty and refer to default\n\n" + colors.normal print "Available services to brute-force:" for serv in services: srv = serv for prt in services[serv]: iplist = services[serv][prt] port = prt plist = len(iplist) print "Service: " + colors.green + str( serv) + colors.normal + " on port " + colors.red + str( port) + colors.normal + " with " + colors.red + str( plist) + colors.normal + " hosts" args.service = raw_input( '\n' + colors.lightblue + 'Enter services you want to brute - default all (ssh,ftp,etc): ' + colors.red) args.threads = raw_input( colors.lightblue + 'Enter the number of parallel threads (default is 2): ' + colors.red) args.hosts = raw_input( colors.lightblue + 'Enter the number of parallel hosts to scan per service (default is 1): ' + colors.red) if args.passlist is None or args.userlist is None: customword = raw_input( colors.lightblue + 'Would you like to specify a wordlist? (y/n): ' + colors.red) if customword == "y": readline.set_completer_delims('\t') readline.parse_and_bind("tab: complete") readline.set_completer(t.pathCompleter) if args.userlist is None and args.username is None: args.userlist = raw_input( colors.lightblue + 'Enter a userlist you would like to use: ' + colors.red) if args.userlist == "": args.userlist = None if args.passlist is None and args.password is None: args.passlist = raw_input( colors.lightblue + 'Enter a passlist you would like to use: ' + colors.red) if args.passlist == "": args.passlist = None if args.username is None or args.password is None: singluser = raw_input( colors.lightblue + 'Would to specify a single username or password (y/n): ' + colors.red) if singluser == "y": if args.username is None and args.userlist is None: args.username = raw_input(colors.lightblue + 'Enter a username: '******'Enter a password: ' + colors.red) if args.password == "": args.password = None if args.service == "": args.service = "all" if args.threads == "": args.threads = "2" if args.hosts == "": args.hosts = "1" print colors.normal
def MainMenu(self, showMessage=True, args=None): """ Main interactive menu for payload generation. showMessage = reset the screen and show the greeting message [default=True] oneRun = only run generation once, returning the path to the compiled executable used when invoking the framework from an external source """ self.outputFileName = "" cmd = "" try: while cmd == "" and self.outputFileName == "": # set out tab completion for the appropriate modules on each run # as other modules sometimes reset this comp = completers.MainMenuCompleter(self.commands, self.payloads) readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(comp.complete) if showMessage: # print the title, where we are, and number of payloads loaded if settings.TERMINAL_CLEAR != "false": messages.title() print " Main Menu\n" print "\t" + helpers.color(str(len(self.payloads))) + " payloads loaded\n" messages.helpmsg(self.commands, showTitle=False) showTitle=False cmd = raw_input(' [menu>>]: ').strip() # handle our tab completed commands if cmd.startswith("help"): if settings.TERMINAL_CLEAR != "false": messages.title() cmd = "" showMessage=False elif cmd.startswith("use"): if len(cmd.split()) == 1: if settings.TERMINAL_CLEAR != "false": messages.title() self.ListPayloads() showMessage=False cmd = "" elif len(cmd.split()) == 2: # pull out the payload/number to use p = cmd.split()[1] # if we're choosing the payload by numbers if p.isdigit() and 0 < int(p) <= len(self.payloads): x = 1 for (name, pay) in self.payloads: # if the entered number matches the payload #, use that payload if int(p) == x: self.payload = pay self.payloadname = name self.outputFileName = self.PayloadMenu(self.payload, args=args) x += 1 # else choosing the payload by name else: for (payloadName, pay) in self.payloads: # if we find the payload specified, kick off the payload menu if payloadName == p: self.payload = pay self.payloadname = payloadName self.outputFileName = self.PayloadMenu(self.payload, args=args) cmd = "" if settings.TERMINAL_CLEAR != "false": showMessage = True # error catchings if not of form [use BLAH] else: cmd = "" showMessage=False elif cmd.startswith("update"): self.UpdateVeil() if settings.TERMINAL_CLEAR != "false": showMessage = True cmd = "" elif cmd.startswith("checkvt"): self.CheckVT() if settings.TERMINAL_CLEAR != "false": showMessage = True cmd = "" # clean payload folders if cmd.startswith("clean"): self.CleanPayloads() if settings.TERMINAL_CLEAR != "false": showMessage = True cmd = "" elif cmd.startswith("info"): if len(cmd.split()) == 1: if settings.TERMINAL_CLEAR != "false": showMessage = True cmd = "" elif len(cmd.split()) == 2: # pull out the payload/number to use p = cmd.split()[1] # if we're choosing the payload by numbers if p.isdigit() and 0 < int(p) <= len(self.payloads): x = 1 for (name, pay) in self.payloads: # if the entered number matches the payload #, use that payload if int(p) == x: self.payload = pay self.payloadname = name self.PayloadInfo(self.payload) x += 1 # else choosing the payload by name else: for (payloadName, pay) in self.payloads: # if we find the payload specified, kick off the payload menu if payloadName == p: self.payload = pay self.payloadname = payloadName self.PayloadInfo(self.payload) cmd = "" showMessage=False # error catchings if not of form [use BLAH] else: cmd = "" showMessage=False elif cmd.startswith("list") or cmd.startswith("ls"): if len(cmd.split()) == 1: if settings.TERMINAL_CLEAR != "false": messages.title() self.ListPayloads() cmd = "" showMessage=False elif cmd.startswith("exit") or cmd.startswith("q"): if self.oneRun: # if we're being invoked from external code, just return # an empty string on an exit/quit instead of killing everything return "" else: print helpers.color("\n [!] Exiting...\n", warning=True) sys.exit() # select a payload by just the number elif cmd.isdigit() and 0 < int(cmd) <= len(self.payloads): x = 1 for (name, pay) in self.payloads: # if the entered number matches the payload #, use that payload if int(cmd) == x: self.payload = pay self.payloadname = name self.outputFileName = self.PayloadMenu(self.payload, args=args) x += 1 cmd = "" if settings.TERMINAL_CLEAR != "false": showMessage = True # if nothing is entered else: cmd = "" showMessage=False # if we're looping forever on the main menu (Veil.py behavior) # reset the output filname to nothing so we don't break the while if not self.oneRun: self.outputFileName = "" return self.outputFileName # catch any ctrl + c interrupts except KeyboardInterrupt: if self.oneRun: # if we're being invoked from external code, just return # an empty string on an exit/quit instead of killing everything return "" else: print helpers.color("\n\n [!] Exiting...\n", warning=True) sys.exit()
def __init__(self, definitions, colors, want_readline, want_completion): super(TerminalShell, self).__init__("<stdin>") self.input_encoding = locale.getpreferredencoding() self.lineno = 0 # Try importing readline to enable arrow keys support etc. self.using_readline = False try: if want_readline: import readline self.using_readline = sys.stdin.isatty() and sys.stdout.isatty( ) self.ansi_color_re = re.compile("\033\\[[0-9;]+m") if want_completion: readline.set_completer(lambda text, state: self. complete_symbol_name(text, state)) # Make _ a delimiter, but not $ or ` readline.set_completer_delims( " \t\n_~!@#%^&*()-=+[{]}\\|;:'\",<>/?") readline.parse_and_bind("tab: complete") self.completion_candidates = [] except ImportError: pass # Try importing colorama to escape ansi sequences for cross platform # colors try: from colorama import init as colorama_init except ImportError: colors = "NoColor" else: colorama_init() if colors is None: terminal_supports_color = (sys.stdout.isatty() and os.getenv("TERM") != "dumb") colors = "Linux" if terminal_supports_color else "NoColor" color_schemes = { "NOCOLOR": (["", "", "", ""], ["", "", "", ""]), "LINUX": ( ["\033[32m", "\033[1m", "\033[22m", "\033[39m"], ["\033[31m", "\033[1m", "\033[22m", "\033[39m"], ), "LIGHTBG": ( ["\033[34m", "\033[1m", "\033[22m", "\033[39m"], ["\033[31m", "\033[1m", "\033[22m", "\033[39m"], ), } # Handle any case by using .upper() term_colors = color_schemes.get(colors.upper()) if term_colors is None: out_msg = "The 'colors' argument must be {0} or None" print(out_msg.format(repr(list(color_schemes.keys())))) quit() self.incolors, self.outcolors = term_colors self.definitions = definitions