def run_console(self, lines=[]): """Run the console. This method is the main loop for executing commands. For all subclassed classes, the user need only call this method to execute an interactive shell or execute commands and exit. It can be used in three modes: 1) it can process commands passed via lines list 2) it can process commands passed via a pipe to the python exec 3) it can prompt for commands and execute them as entered Modes (1) and (2) execute all commands then exit. lines[in] If not empty, execute the list of commands. """ # If we have commands issued by the command line, execute and exit. if self.commands is not None: command_list = self.commands.split(';') for command in command_list: command = command.strip('\n').strip(' ') if os.name == 'nt': command = command.strip('"') if self._do_command(command.strip('"')): break # If we have piped input, read the input by line and execute elif not os.isatty(sys.stdin.fileno()) or len(lines) > 0: for command in sys.stdin.readlines(): command_list = command.split(';') for cmd in command_list: cmd = cmd.strip('\n').strip(' ') if os.name == 'nt': cmd = cmd.strip('"') if self._do_command(cmd.strip('"')): break # Otherwise, we are in an interactive mode where we get a command # from the user and execute else: cmd = '' if not self.quiet: print self.options.get('welcome', 'Welcome to the console!\n') while cmd.lower() not in ['exit', 'quit']: command = self.get_user_command() self.history.add(command) if self._do_command(command): break if not self.quiet: print self.options.get('goodbye', 'Thanks for using the console.\n')
def do_reset(self, cmd): "reset [scancounter | crackcounter] ... reset specified counter to 0" if cmd.strip() == "": self.print_error('You need to specify what should be reset!') elif cmd.strip() == "scancounter": self.SCANNED_TILL = 0 print(f"{Fore.GREEN}Scancounter set to 0!{Style.RESET_ALL}") elif cmd.strip() == "crackcounter": self.CRACKED_TILL = 0 print(f"{Fore.GREEN}Crackcounter set to 0!{Style.RESET_ALL}") else: self.print_error('Unknown input: "' + cmd + '"') print("")
def do_shell(self, cmd): 'shell [command] ... run the command in the system shell\n! [command] ....... shortcut of "shell" \n' if cmd.strip() == "": self.print_error("You need to enter a command to run!") print() return result = os.popen(cmd).read() print(f"{Fore.YELLOW}{result}{Style.RESET_ALL}")
def get_git_commands(): """Get git commands from 'git help' output.""" names = [] output = check_output(["git", "help", "-a"]) for s in output.split('\n')[8:-2]: names.extend(cmd.strip() for cmd in s.split()) return sorted(names)
def _parseFirstArg(cmd): cmd = cmd.strip() if cmd.startswith('"'): # The .replace() is to ensure it does not mistakenly find the # second '"' in, say (escaped quote): # "C:\foo\"bar" arg1 arg2 idx = cmd.replace('\\"', 'XX').find('"', 1) if idx == -1: raise WinIntegError("Malformed command: %r" % cmd) first, rest = cmd[1:idx], cmd[idx+1:] rest = rest.lstrip() else: if ' ' in cmd: first, rest = cmd.split(' ', 1) else: first, rest = cmd, "" return first
def _do_command(self, command): """Execute a command This method routes the command to the appropriate methods for execution. command[in] Command to execute Returns bool True - exit utility, False - do not exit """ # do variable replacement command = self._replace_variables(command.strip(' ')) if self.options.get('verbosity', False): print "\nExecuting command:", command # process simple commands if command.lower().startswith('set '): self._add_variable(command[4:]) if not self.quiet: print elif command[0:14].lower() == 'show variables': self.variables.show_variables() elif self.custom_commands and \ command[0:12].lower() == 'show options': self.show_custom_options() else: cmd, parameters = self._get_util_parameters(command) cmd = cmd.strip() parameters = parameters.strip() if cmd.lower() == 'help': self.show_help(parameters) self.cmd_line.clear() self.tab_count = 0 elif cmd == '': print elif cmd.lower() in ['exit', 'quit']: print return True elif self.custom_commands: if not self.is_valid_custom_command(cmd): print "\n\nUnknown command: %s %s\n" % (cmd, parameters) else: try: self.execute_custom_command(cmd, parameters) print except UtilError, err: print err.errmsg
def do_exec(self, line): "Execute a Ravel script" if os.path.isdir(line): print "ravel: {0}: Is a directory".format(line) return if not os.path.isfile(line): print "ravel: {0}: No such file or directory".format(line) return with open(line) as f: for cmd in f.readlines(): cmd = cmd.strip() if cmd == "" or cmd[0] == "#": continue print "{0}{1}".format(RavelConsole.prompt, cmd) self.onecmd(cmd) # may need to wait for flows/database changes time.sleep(0.5)
def run(self): self.parseArgs() self.login("init") me = ActParser.getInstance() print(CMD_HELP) while True: if self.tag: cmd = self.tag self.tag = '' else: cmd = raw_input('\nCMD (?, ctrl+]) $ ') cmd = cmd.strip() if not cmd: print(CMD_HELP) if not self.is_connect(): self.login("again for disconnect") if self.is_connect(): self.dut.sendline("") self.dut.interact() #self.thread_interact() continue elif cmd == 'exit' or cmd == 'quit': break elif cmd == 'test': self.dut.parse_log(3) continue else: if not self.is_connect(): self.login("again for disconnect") ret = me.action_execute(self.dut, [cmd]) log.info("dut execute %s return %s.", cmd, ret) if ret and self.is_connect(): self.dut.sendline("") self.dut.interact() #self.thread_interact() continue
def default(self, cmd): cmd = cmd.strip() if cmd == 'EOF': # EOF means exit. print a new line to clean up print return True if not cmd.endswith(';'): cmd = self.multiline(cmd).strip() # if there are multiple statements on one line, split them up if ';' in cmd: # split up the command and execute each part complete, partial = cmd.split(';', 1) if partial: # if there are two or more commands, run the first self.default(complete + ';') return self.default(partial) if not cmd: # no sql, noop return False start = time.time() # execute the SQL command try: # a weak attempt to see if we have any %(keyword)s to expand if r'%(' in cmd: cmd = cmd % self.db.keywords self.cu.execute(cmd) except sqlerrors.DatabaseError, e: if len(e.args) > 1: print 'Error:', str(e.args[0]) else: print 'Error:', str(e) return False
def main(): parser = argparse.ArgumentParser() parser.add_argument("-c", "--command", help="execute given commands (separated by ;)", default=None, nargs="*") parser.add_argument("-s", "--script", help="execute commands from file", default=None) parser.add_argument("-n", "--noninteractive", help="non interactive mode (don't enter shell)", action="store_true", default=False) parser.add_argument("--nocolor", help="disable color", action="store_true", default=False) parser.add_argument("--nocache", help="disable cache", action="store_true", default=False) parser.add_argument("--logfile", help="write log to file", default=None) parser.add_argument( "--loglevel", help="loglevel (CRITICAL, ERROR, WARNING, INFO, DEBUG)", default="INFO") parser.add_argument( "--reset", help="hard reset device via DTR (serial connection only)", action="store_true", default=False) parser.add_argument("-o", "--open", help="directly opens board", metavar="BOARD", action="store", default=None) parser.add_argument("board", help="directly opens board", nargs="?", action="store", default=None) args = parser.parse_args() format = '%(asctime)s\t%(levelname)s\t%(message)s' if args.logfile is not None: logging.basicConfig(format=format, filename=args.logfile, level=args.loglevel) else: logging.basicConfig(format=format, level=logging.CRITICAL) logging.info('Micropython File Shell v%s started' % version.FULL) logging.info('Running on Python %d.%d using PySerial %s' \ % (sys.version_info[0], sys.version_info[1], serial.VERSION)) mpfs = MpFileShell(not args.nocolor, not args.nocache, args.reset) if args.open is not None: if args.board is None: mpfs.do_open(args.open) else: print("Positional argument ({}) takes precedence over --open.". format(args.board)) if args.board is not None: mpfs.do_open(args.board) if args.command is not None: for cmd in ' '.join(args.command).split(';'): scmd = cmd.strip() if len(scmd) > 0 and not scmd.startswith('#'): mpfs.onecmd(scmd) elif args.script is not None: f = open(args.script, 'r') script = "" for line in f: sline = line.strip() if len(sline) > 0 and not sline.startswith('#'): script += sline + '\n' if sys.version_info < (3, 0): sys.stdin = io.StringIO(script.decode('utf-8')) else: sys.stdin = io.StringIO(script) mpfs.intro = '' mpfs.prompt = '' if not args.noninteractive: try: mpfs.cmdloop() except KeyboardInterrupt: print("")
def main(): parser = argparse.ArgumentParser() parser.add_argument("-c", "--command", help="execute given commands (separated by ;)", default=None, nargs="*") parser.add_argument("-s", "--script", help="execute commands from file", default=None) parser.add_argument("-n", "--noninteractive", help="non interactive mode (don't enter shell)", action="store_true", default=False) parser.add_argument("--nocolor", help="disable color", action="store_true", default=False) parser.add_argument("--nocache", help="disable cache", action="store_true", default=False) parser.add_argument("--logfile", help="write log to file", default=None) parser.add_argument("--loglevel", help="loglevel (CRITICAL, ERROR, WARNING, INFO, DEBUG)", default="INFO") parser.add_argument("--reset", help="hard reset device via DTR (serial connection only)", action="store_true", default=False) parser.add_argument("-o", "--open", help="directly opens board", metavar="BOARD", action="store", default=None) parser.add_argument("board", help="directly opens board", nargs="?", action="store", default=None) args = parser.parse_args() format = '%(asctime)s\t%(levelname)s\t%(message)s' if args.logfile is not None: logging.basicConfig(format=format, filename=args.logfile,level=args.loglevel) else: logging.basicConfig(format=format, level=logging.CRITICAL) logging.info('Micropython File Shell v%s started' % version.FULL) logging.info('Running on Python %d.%d using PySerial %s' \ % (sys.version_info[0], sys.version_info[1], serial.VERSION)) mpfs = MpFileShell(not args.nocolor, not args.nocache, args.reset) if args.open is not None: if args.board is None: mpfs.do_open(args.open) else: print("Positional argument ({}) takes precedence over --open.".format(args.board)) if args.board is not None: mpfs.do_open(args.board) if args.command is not None: for cmd in ' '.join(args.command).split(';'): scmd = cmd.strip() if len(scmd) > 0 and not scmd.startswith('#'): mpfs.onecmd(scmd) elif args.script is not None: f = open(args.script, 'r') script = "" for line in f: sline = line.strip() if len(sline) > 0 and not sline.startswith('#'): script += sline + '\n' if sys.version_info < (3, 0): sys.stdin = io.StringIO(script.decode('utf-8')) else: sys.stdin = io.StringIO(script) mpfs.intro = '' mpfs.prompt = '' if not args.noninteractive: try: mpfs.cmdloop() except KeyboardInterrupt: print("")
def parse(self, cmd): return tuple(cmd.strip().split())
def enter_command(): cmd = raw_input('Enter command (? for help) : ') cmd = cmd.strip().lower() return cmd
finally: if self.use_rawinput and self.completekey: try: import readline readline.set_completer(self.old_completer) except ImportError: pass if __name__ == "__main__": parser = OptionParser() parser.add_option("-f", type="string", dest="file") (options, args) = parser.parse_args() shell = InjectShell() if options.file: with open(options.file, "r") as fh: cmds = fh.readlines() for cmd in [cmd.strip() for cmd in cmds]: if len(cmd) > 0: print "%s%s" % (shell.prompt, cmd) shell.onecmd(cmd) for cmd in args: print "%s%s" % (shell.prompt, cmd) shell.onecmd(cmd) shell.cmdloop()
def main(argv): # Parse command line arguments parser = commonUtils.MainCmdArgParser(APC_HOME, 'Console arguments.', 'console') parser.add_argument('--cmd', help="Execute a single command in batch mode") parser.add_argument('-f', '--filename', help="Execute all cmds inside the file") parser.add_argument('-i', '--interactive', type=bool, default=True, help="Interactive mode") parser.add_argument('-n', '--name', help="APC client-id") args = parser.parse_args() if not args: print parser.errmsg sys.exit(1) endPoints = commonUtils.ApiEndpointBuilder(APC_HOME, args.api_proto, args.api_ipcpath, args.api_host, args.api_port) if args.name: APC_ENDPOINT = endPoints.getClientEndpoint('APC_ENDPOINT_PATH', args.name) APC_LOG_ENDPOINT = endPoints.getClientEndpoint('APC_LOG_ENDPOINT_PATH', args.name) else: # if there is only one APC running, connec to it numApcRunning = 0 apcInfo = [] for proc in psutil.process_iter(): try: pInfo = proc.as_dict(attrs=['pid', 'name', 'cmdline']) if pInfo['name'] == 'apc': numApcRunning = numApcRunning + 1 apcInfo = pInfo except psutil.NoSuchProcess: pass if numApcRunning == 0: print "APC is not running, please use apcctl to start APC then try again." sys.exit(1) elif numApcRunning == 1: try: location = apcInfo['cmdline'].index('--client-id') # the APC client-id value is the next APCName = apcInfo['cmdline'][location + 1] APC_ENDPOINT = endPoints.getClientEndpoint( 'APC_ENDPOINT_PATH', APCName) APC_LOG_ENDPOINT = endPoints.getClientEndpoint( 'APC_LOG_ENDPOINT_PATH', APCName) except ValueError: print "APC is running without client-id, please check." sys.exit(1) else: print "{0} APCs are running, don't know which one to connect to. Please retry with -n option.".format( numApcRunning) sys.exit(1) ctx = zmq.Context() # Print BANNER print BANNER # apc RPC client apc = ApcClient(ctx, APC_ENDPOINT) rpcClientsDic = {APC_CLIENT_NAME: apc} # Notification listeners log_console = NoSecLogConsole(ctx, "logListener", APC_LOG_ENDPOINT, rpcClientsDic[APC_CLIENT_NAME]) listenersDic = {'logListener': log_console} commander = CommandLineHandler(rpcClientsDic, listenersDic) if args.cmd: l = commander.precmd(args.cmd) r = commander.onecmd(l) r = commander.postcmd(r, l) if not args.interactive: #To unsubscribe listeners(stop threads). commander.unsubscribeAllListeners() elif args.filename: try: fd = open(args.filename, 'r') printInfo('Loading commands from {0}'.format(args.filename)) for cmd in fd: cmd = cmd.strip() if cmd.startswith('#'): continue printInfo('exec: {0}'.format(cmd)) l = commander.precmd(cmd) r = commander.onecmd(l) r = commander.postcmd(r, l) fd.close() except IOError as exc: printError("FILE_NOT_FOUND", str(exc)) if not args.interactive: #To unsubscribe listeners(stop threads). commander.unsubscribeAllListeners() else: try: commander.cmdloop() except: print "Command failed, please check if APC is running" # Close listeners and RPC clients log_console.close()