Esempio n. 1
0
 def __init__(self, conf_file,
              custom_api=None,
              custom_print=None,
              custom_repr_as_table=None):
     Cmd.__init__(self)
     here = os.path.abspath(os.path.dirname(conf_file))
     self.config = ConfigParser(defaults={'here': here})
     self.config.read(conf_file)
     db_string = self.config.get('app:lasco', 'lasco.db_string')
     self.engine = create_engine(db_string)
     self.session = sessionmaker(self.engine)()
     # The following customizations are here for our tests.
     if custom_api:
         self.api = custom_api
     else:
         self.api = ExceptionWrapper(lasco.api)
     if custom_print:
         self.print_ = custom_print
     else:  # pragma: no coverage
         self.print_ = lambda msg: sys.stdout.write(
             msg.encode(DEFAULT_ENCODING) + os.linesep)
     if custom_repr_as_table:
         self.repr_as_table = custom_repr_as_table
     else:  # pragma: no coverage
         self.repr_as_table = repr_as_table
Esempio n. 2
0
 def __init__(self, stdin=sys.stdin, foreground=True):
     self.bridge = None  # default bridge
     self.ipt = None
     self.nss = None
     self.dvr = None
     if foreground:
         self.prompt = color_str(PROMPT_KW, 'g')
         self.stdin = stdin
         self.in_poller = poll()
         self.in_poller.register(stdin)
         Cmd.__init__(self)
         output("***\n Welcome to EasyOVS %s, "
                "type help to see available cmds.\n***\n" % VERSION)
         info('*** Starting CLI:\n')
         debug("==Loading credentials==\n")
         debug("auth_url = %s\n" % os.getenv('OS_AUTH_URL') or
               cfg.CONF.OS.auth_url)
         debug("username = %s\n" % os.getenv('OS_USERNAME') or
               cfg.CONF.OS.username)
         passwd = os.getenv('OS_PASSWORD') or cfg.CONF.OS.password
         passwd = passwd[:len(passwd)/4] + "****" + passwd[-len(passwd)/4:]
         debug("password = %s\n" % passwd)
         debug("tenant_name = %s\n" % os.getenv('OS_TENANT_NAME') or
               cfg.CONF.OS.tenant_name)
         while True:
             try:
                 #if self.isatty():
                 #quietRun( 'stty sane' )
                 self.cmdloop()
                 break
             except KeyboardInterrupt:
                 info('\nInterrupt\n')
Esempio n. 3
0
   def __init__(self, completekey='tab', stdin=None, stdout=None):
      Cmd.__init__(self, completekey, stdin, stdout)
     
      # base wafterpreter constants
      self.intro = "Welcome to Bywaf"      
      self.base_prompt = "Bywaf" 
      self.set_prompt('') # set the prompt
      self.delegate_input_handler = None # no delegated input by default
      
      # currently loaded plugins, loaded & selected with he "use" command.
      # is a dictionary of { "plugin_name" : loaded_module_object }
      self.plugins = {}  
      
      # dictionary of global variable names and values
      self.global_options = {} 
      
      # jobs are spawned using this object's "submit()"
#      self.job_executor = concurrent.futures.ProcessPoolExecutor(DEFAULT_MAX_CONCURRENT_JOBS)      
      self.job_executor = concurrent.futures.ThreadPoolExecutor(DEFAULT_MAX_CONCURRENT_JOBS)

      # running counter, increments with every job; used as Job ID
      self.job_counter = 0 
      
      # job pool (list of runnign and completed Futures objects)      
      self.jobs = []  

      # currently-selected plugin's name and object (reference to a job in self.jobs)
      self.current_plugin = None
      self.current_plugin_name = ''
      
      # list of newly-finished backgrounded plugin command jobs
      self.finished_jobs = []
Esempio n. 4
0
 def __init__( self, mininet, stdin=sys.stdin, script=None ):
     self.mn = mininet
     self.nodelist = self.mn.controllers + self.mn.switches + self.mn.hosts
     self.nodemap = {}  # map names to Node objects
     for node in self.nodelist:
         self.nodemap[ node.name ] = node
     # Attempt to handle input
     self.stdin = stdin
     self.inPoller = poll()
     self.inPoller.register( stdin )
     self.inputFile = script
     Cmd.__init__( self )
     info( '*** Starting CLI:\n' )
     if self.inputFile:
         self.do_source( self.inputFile )
         return
     while True:
         try:
             # Make sure no nodes are still waiting
             for node in self.nodelist:
                 while node.waiting:
                     node.sendInt()
                     node.monitor()
             if self.isatty():
                 quietRun( 'stty sane' )
             self.cmdloop()
             break
         except KeyboardInterrupt:
             output( '\nInterrupt\n' )
Esempio n. 5
0
 def do_help(self, line):
     """
     Describe available CLI commands.
     """
     Cmd.do_help(self, line)
     if line is "":
         output(self.helpStr)
Esempio n. 6
0
 def __init__(self, host='localhost', port=61613, user='', passcode='', ver='1.1', prompt='> ', verbose=True, use_ssl=False, stdin=sys.stdin, stdout=sys.stdout):
     Cmd.__init__(self, 'Tab', stdin, stdout)
     ConnectionListener.__init__(self)
     self.prompt = prompt
     self.verbose = verbose
     self.user = user
     self.passcode = passcode
     self.__quit = False
     if ver == '1.0':
         self.conn = StompConnection10([(host, port)], wait_on_receipt=True)
     elif ver == '1.1':
         self.conn = StompConnection11([(host, port)], wait_on_receipt=True)
     elif ver == '1.2':
         self.conn = StompConnection12([(host, port)], wait_on_receipt=True)
     elif ver == 'multicast':
         self.conn = MulticastConnection()
     else:
         raise RuntimeError('Unknown version')
     if use_ssl:
         self.conn.set_ssl([(host, port)])
     self.conn.set_listener('', self)
     self.conn.start()
     self.conn.connect(self.user, self.passcode, wait=True)
     self.transaction_id = None
     self.version = ver
     try:
         self.nversion = float(ver)
     except ValueError:
         self.nversion = 1.0
     self.__subscriptions = {}
     self.__subscription_id = 1
Esempio n. 7
0
 def __init__( self, mininet, stdin=sys.stdin, script=None ):
     self.mn = mininet
     # Local variable bindings for py command
     self.locals = { 'net': mininet }
     # Attempt to handle input
     self.stdin = stdin
     self.inPoller = poll()
     self.inPoller.register( stdin )
     self.inputFile = script
     Cmd.__init__( self )
     info( '*** Starting CLI:\n' )
     if self.inputFile:
         self.do_source( self.inputFile )
         return
     while True:
         try:
             # Make sure no nodes are still waiting
             for node in self.mn.values():
                 while node.waiting:
                     node.sendInt()
                     node.monitor()
             if self.isatty():
                 quietRun( 'stty sane' )
             self.cmdloop()
             break
         except KeyboardInterrupt:
             output( '\nInterrupt\n' )
Esempio n. 8
0
 def do_help(self, args):
     """Get help on commands
        'help' or '?' with no arguments prints a list of commands for which help is available
        'help <command>' or '? <command>' gives help on <command>
     """
     ## The only reason to define this method is for the help text in the doc string
     Cmd.do_help(self, args)
Esempio n. 9
0
    def __init__(self, ctrl):
        Cmd.__init__(self)
        self._ctrl = ctrl
        self._changeset = ChangeSet(ctrl.getCache())

        self._undo = []
        self._redo = []
Esempio n. 10
0
 def __init__(self,world = None,game_out_q=None, stdin=sys.stdin, parent=None):
     Cmd.__init__(self)
     self.use_rawinput = False
     self.parent = parent
     self.game_out_q = game_out_q
     self.exit = False
     print(str(__name__) + ' using input %s' % self.stdin)
Esempio n. 11
0
    def do_help(self, args):
        """Override the help command to handle cases of command arguments.
        
        General help is provided by help_*() methods."""
        if len(args.split()) < 2:
            Cmd.do_help(self, args)
        else:
            if args == 'talk show':
                print Help.TALK_SHOW_TALKS
            elif args == 'talk show events':
                print Help.TALK_SHOW_EVENTS
	    elif args == 'talk remove':
		print Help.TALK_REMOVE
	    elif args == 'talk add':
		print Help.TALK_ADD
	    elif args == 'talk update':
		print Help.TALK_UPDATE
	    elif args == 'config show':
		print Help.CONFIG_SHOW
	    elif args == 'config set audio':
		print Help.CONFIG_SET_AUDIO
	    elif args == 'config set video':
		print Help.CONFIG_VIDEO_SET
	    elif args == 'config set video resolution':
		print Help.CONFIG_VIDEO_RESOLUTION_SET
	    elif args == 'config set dir':
		print Help.CONFIG_DIR_SET
	    elif args == 'config set streaming':
		print Help.CONFIG_SET_STREAMING
	    elif args == 'config set file':
		print Help.CONFIG_SET_FILE
	    elif args == 'config set':
		print Help.CONFIG_SET
            else:
                print 'Unknown %s topic' % (args)
Esempio n. 12
0
    def __init__(self, client):
        if issubclass(Cmd, object):
            super().__init__()
        else:
            Cmd.__init__(self)

        self.client = client
Esempio n. 13
0
    def __init__(self, site_config=None):
        Cmd.__init__(self)
        self.__site_config = site_config

        shell_context = ShellContext(self)
        self.__shell_context = shell_context

        self.__history_file = os.path.join(os.path.expanduser("~/.ertshell/ertshell.history"))
        self.__init_history()

        matplotlib.rcParams["backend"] = "Qt4Agg"
        matplotlib.rcParams["interactive"] = True
        matplotlib.rcParams["mathtext.default"] = "regular"
        matplotlib.rcParams["verbose.level"] = "helpful"
        matplotlib.rcParams["verbose.fileo"] = "sys.stderr"


        try:
            matplotlib.style.use("ggplot") # available from version 1.4
        except AttributeError:
            pass

        Debug(shell_context)
        PlotSettings(shell_context)
        Workflows(shell_context)
        Cases(shell_context)
        Plugins(shell_context)
        SummaryKeys(shell_context)
        GenDataKeys(shell_context)
        GenKWKeys(shell_context)
        Results(shell_context)
Esempio n. 14
0
def print_menu(arr):
	global buffered
	"""Main menu printer
	   @param arr is the menu array to print.  Fetches input, 
		parses and built-in command keywords, and returns the selected idx.
	"""

	if not buffered is None:
		# buffered input, return
		if len(buffered) > 0: 
			return buffered.pop(0)
		else:	
			buffered = None

	tmp = Cmd()
	arr = ['\t[%d] %s'%(x+1,arr[x]) for x in xrange(len(arr))] 
	tmp.columnize(arr,35)
	print '\n0) Back'
	try:
		choice = raw_input('> ')
		choice = check_opts(choice)

		# buffered input
		if choice > 1:
			choice = choice.split(' ')
			buffered = []
			for entry in choice[1:]:
				buffered.append(int(entry))
			choice = int(choice[0])
	except KeyboardInterrupt: choice = -1
	except Exception, e:
		debug(e)	
		os.system('clear')
		choice = -1
Esempio n. 15
0
 def do_help(self, arg):
     if arg:
         Cmd.do_help(self, arg)
     else:
         # Everything from here to the end is lifted straight
         # out of cmd.Cmd.do_help()
         names = self.get_names()
         cmds_doc = []
         cmds_undoc = []
         help = {}
         for name in names:
             if name[:5] == 'help_':
                 help[name[5:]]=1
         names.sort()
         # There can be duplicates if routines overridden
         prevname = ''
         for name in names:
             if name[:3] == 'do_':
                 if name == prevname:
                     continue
                 prevname = name
                 cmd=name[3:]
                 if cmd in help:
                     cmds_doc.append(cmd)
                     del help[cmd]
                 elif getattr(self, name).__doc__:
                     cmds_doc.append(cmd)
                 else:
                     cmds_undoc.append(cmd)
         self.stdout.write("%s\n"%str(self.doc_leader))
         self.print_topics(self.doc_header,   cmds_doc,   15,80)
         self.print_topics(self.misc_header,  help.keys(),15,80)
Esempio n. 16
0
    def __init__(self, framework, plugins_path):
        Cmd.__init__(self)
        self._framework = framework
        self._plugins_path = os.path.abspath(plugins_path)
        sys.path.append(self._plugins_path)

        self._config = configparser.ConfigParser()
        config_fn = os.path.join(self._plugins_path, 'config.ini')
        if os.path.exists(config_fn):
            self._config.read(config_fn)

        for section in self._config.sections():
            try:
                _f = self._framework.install_bundle(section)
                if self._config.get(section, 'start'):
                    _f.result().start().result()
            except configparser.NoOptionError:
                pass
            except BaseException as e:
                print('  bundle {0} init error:'.format(section), e)
                self._config.remove_section(section)


        self.intro = 'Gumpy runtime console'
        self.prompt = '>>> '
Esempio n. 17
0
 def do_help(self, cmd=None):
     Cmd.do_help(self, cmd)
     if not cmd or not self.show_usage:
         return
     do_ = getattr(self, "do_" + cmd, None)
     if not do_ or hasattr(self, "help_ " + cmd):
         return
     while (hasattr(do_, "__wrapped__") and
            not getattr(do_, USE_MY_ANNOTATIONS, None)):
         do_ = do_.__wrapped__
     if getattr(do_, GETS_RAW, None):
         return
     spec = getfullargspec(do_)
     args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
     non_kw_args = args[:-len(defaults)] if defaults else args
     kw_args = args[-len(defaults):] if defaults else []
     if not defaults:
         defaults = []
     if not kwonlydefaults:
         kwonlydefaults = {}
     helpstr = "\t" + cmd
     for arg, default in kwonlydefaults.items():
         helpstr += " [-{0} {1}(={2})]".format(arg, arg[0].upper(), default)
     for arg, default in zip(kw_args, defaults):
         helpstr += " [{0}(={1})]".format(arg.upper(), default)
     for arg in non_kw_args[1:]:
         helpstr += " {0}".format(arg.upper())
     if varargs:
         helpstr += " [{0}]".format(varargs.upper())
     self.stdout.write(helpstr + "\n")
Esempio n. 18
0
    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()
Esempio n. 19
0
 def __init__(self, corpus, dictionary, model, possible_matches=None):
     Cmd.__init__(self)
     self.prompt = "> "
     self.corpus = corpus
     self.dictionary = dictionary
     self.model = model
     self.possible_matches = possible_matches
Esempio n. 20
0
 def __init__(self, settings):
     Cmd.__init__(self)
     self.SETTINGS = settings
     self.commands = []
     for s in dir(self):
         if re.match(r'do_',s):
             self.commands.append(re.sub(r'do_','',s))
 def __init__(self, image, completekey='tab', stdin=None, stdout=None):
     Cmd.__init__(self, completekey=completekey, stdin=stdin, stdout=stdout)
     self.curdir = "/"
     self.rdisk = None
     if image.filename == "remote":
         self.rdisk = RamdiskToolClient.get()
     self.device_infos = image.device_infos
     self.complete_open = self._complete
     self.complete_xattr = self._complete
     self.complete_cprotect = self._complete
     self.complete_ls = self._complete
     self.complete_cd = self._complete
     self.complete_plist = self._complete
     self.complete_xxd = self._complete
     self.image = image
     if image.ppn and image.filename == "remote":
         self.savepath = "."
         print "Remote PPN device, use nand_dump + save, other commands will fail"
         return
     self.system = image.getPartitionVolume(0)
     self.data = image.getPartitionVolume(1)
     self.volume = None
     self.volname = ""
     grab_system_version(self.system, self.device_infos)
     print "Keybag state: %slocked" % (int(self.data.keybag.unlocked) * "un")
     self.deviceName = get_device_name(self.data)
     self.do_data("")
     self.savepath = os.path.join(os.path.dirname(image.filename), "%s.plist" % self.device_infos.udid[:10])
     #if image.iosVersion > 3 and not image.device_infos.has_key("passcode"):
     #    print "No passcode found in plist file, bruteforce required to access protected data"
     
     self.carver = None
Esempio n. 22
0
 def __init__(self,casename,bench, sutnames , logfiledir, outputfile =None):
     if outputfile:
         pass
     else:
         outputfile=sys.stdout
     self.benchinfo = bench2dict(bench)
     #self.benchinfo = benchinfo
     self.casename =casename
     self.sut ={}
     for sutname in sutnames:
         self.sut.update({sutname:self.benchinfo[sutname]})
     steps=[[],[],[]]
     mode ='FULL'
     self.tc= Case(casename,self.sut,steps=[[],[],[]],mode='FULL',DebugWhenFailed=False,logdir=logfiledir,caseconfigfile='../lib/case.cfg')
     self.thQureyOut = threading.Thread(target=self.QureyOutput,args = [] )#outputfile
     self.thQureyOut.start()
     self.client ='interaction'
     self.tc.AddClient(self.client)
     self.tc.troubleshooting()
     nowTime =time.time()
     self.lastCmdIssueTime=nowTime
     Cmd.__init__(self, 'tab', sys.stdin, sys.stdout)
     self.use_rawinput=True
     #import readline
     #readline.set_completer_delims('\t\n')
 #     def do_set(self,name):
 #         print(name)
     self.do_setsut(self.tc.Session.keys()[-1])
     self.helpDoc={}
     self.cmdbank=[]
Esempio n. 23
0
 def __init__(self):
     Cmd.__init__(self)
     self.prompt = "\x1b[1;34m%s\x1b[0m> " % "torrent-sentinel"
     self.emptyline = lambda : 0
     self.ruler = ''
     self.complete_info = self.complete_search
     self.complete_download = self.complete_search
Esempio n. 24
0
    def __init__(self, memobj, config=None, symobj=None):

        self.extcmds = {}
        self.basecmds = []
        self.emptymeth = None
        self.extsubsys = collections.defaultdict(list)
        self.scriptpaths = []
        self.addScriptPathEnvVar('ENVI_SCRIPT_PATH')

        Cmd.__init__(self, stdout=self)

        for name in dir(self):
            if name.startswith('do_'):
                self.basecmds.append(name[3:])

        self.shutdown = threading.Event()

        # If they didn't give us a resolver, make one.
        if symobj is None:
            symobj = e_resolv.SymbolResolver()

        if config is None:
            config = e_config.EnviConfig(defaults=cfgdefs)

        # Force it to be there if its not
        config.getSubConfig('cli')

        self.config = config
        self.memobj = memobj
        self.symobj = symobj
        self.canvas = e_canvas.MemoryCanvas(memobj, syms=symobj)

        self.aliases = {}  # For *runtime* aliases only!
Esempio n. 25
0
    def __init__(self):
        Cmd.__init__(self)
        self.prompt = '(Subdomainator) > '
        self.do_help.__func__.__doc__ = '''Displays the help menu.'''
        self.doc_header = 'Commands'

        self.menu_state = "main"
Esempio n. 26
0
    def do_help(self, args):
        '''print help on a command'''
        if args.command:
            f = getattr(self, 'help_' + args.command, None)
            if f:
                f()
                return

            f = getattr(self, 'do_' + args.command, None)
            if not f:
                msg = self.nohelp % (args.command,)
                self.stdout.write('{0}\n'.format(msg))
                return

            docstr = getattr(f, '__doc__', None)
            f = getattr(self, 'args_' + args.command, None)
            if f:
                parser = argparse.ArgumentParser(
                    prog=args.command,
                    description=docstr)
                f(parser)
                parser.print_help(file=self.stdout)
            else:
                if not docstr:
                    docstr = self.nohelp % (args.command,)
                self.stdout.write('{0}\n'.format(docstr))
        else:
            Cmd.do_help(self, '')
Esempio n. 27
0
 def do_help(self, args):
     """
        Getting help on "help" is kinda silly dont you think?
     """
     #The only reason to define this method is for the help text in the
     #docstring
     Cmd.do_help(self, args)
Esempio n. 28
0
 def cmdloop(self, intro=""):
     try:
         Cmd.cmdloop(self, intro)
         self.postloop()
     except KeyboardInterrupt:
         print("^C")
         self.cmdloop()
Esempio n. 29
0
 def __init__(self, savedata):
     Cmd.__init__(self)
     self._save_manager = SaveManager(savedata.savefile, savedata.gluid)
     data, self.save_number = self._save_manager.load(savedata.legacy)
     if not savedata.legacy:
         data = decompress_data(data)
     self._xml_handle = XmlHandler(data)
     self._xml_handle.pre_load()
     self.savedata = savedata
     self._show_functions = {
         'currencies': show_currencies,
         'currency': show_currency,
         'ponies': show_ponies,
         'pony': show_pony,
         'zones': show_zones,
         'zone': show_zone,
     }
     self._set_functions = {
         'currency': set_currency,
         'ponies': set_ponies,
         'pony': set_pony,
         'zones': set_zones,
         'zone': set_zone,
         'inventory': set_inventory,
     }
Esempio n. 30
0
    def __init__( self, mininet, stdin=sys.stdin, script=None ):
        """Start and run interactive or batch mode CLI
           mininet: Mininet network object
           stdin: standard input for CLI
           script: script to run in batch mode"""
        
        self.mn = mininet
        # Local variable bindings for py command
        self.locals = { 'net': mininet }
        # Attempt to handle input
        self.stdin = stdin
        self.inPoller = poll()
        self.inPoller.register( stdin )
        self.inputFile = script
        
        
        Cmd.__init__( self )
        info( '*** Starting CLI:\n' )
        
        if self.inputFile:
            self.do_source( self.inputFile )
            return

        self.initReadline()
        self.run()
Esempio n. 31
0
    def onecmd(self, line):
        """Wrapper for Cmd.onecmd() that handles errors.
		Also handles line being a list, to ease execution of a single command from the command line of this app.
		"""
        if isinstance(line, list): line = self.lineFromArgs(line)
        try:
            line = self.precmd(line)
            result = Cmd.onecmd(self, line)
            return result
        except KeyboardInterrupt:
            self.msg("Keyboard interrupt")
        except Exception as e:
            self.msg(err())
            return
Esempio n. 32
0
    def __init__(self, world_list, regionset, options, backup_worlds):
        Cmd.__init__(self)
        self.world_list = world_list
        self.regionset = regionset
        self.world_names = [str(i.name) for i in self.world_list]
        # if there's only one world use it
        if len(self.world_list) == 1 and len(self.regionset) == 0:
            self.current = world_list[0]
        elif len(self.world_list) == 0 and len(self.regionset) > 0:
            self.current = self.regionset
        else:
            self.current = None
        self.options = options
        self.backup_worlds = backup_worlds
        self.prompt = "#-> "
        self.intro = ("Minecraft Region-Fixer interactive mode.\n(Use tab to "
                      "autocomplete. Type help for a list of commands.)\n")

        # Possible args for chunks stuff
        possible_args = ""
        first = True
        for i in list(world.CHUNK_PROBLEMS_ARGS.values()) + ['all']:
            if not first:
                possible_args += ", "
            possible_args += i
            first = False
        self.possible_chunk_args_text = possible_args

        # Possible args for region stuff
        possible_args = ""
        first = True
        for i in list(world.REGION_PROBLEMS_ARGS.values()) + ['all']:
            if not first:
                possible_args += ", "
            possible_args += i
            first = False
        self.possible_region_args_text = possible_args
Esempio n. 33
0
 def __init__(self, casename, bench, sutnames, logfiledir, outputfile=None):
     if outputfile:
         pass
     else:
         outputfile = sys.stdout
     self.benchinfo = bench2dict(bench)
     #self.benchinfo = benchinfo
     self.casename = casename
     self.sut = {}
     for sutname in sutnames:
         self.sut.update({sutname: self.benchinfo[sutname]})
     steps = [[], [], []]
     mode = 'FULL'
     self.tc = Case(casename,
                    self.sut,
                    steps=[[], [], []],
                    mode='FULL',
                    DebugWhenFailed=False,
                    logdir=logfiledir,
                    caseconfigfile='../lib/case.cfg')
     self.thQureyOut = threading.Thread(target=self.QureyOutput,
                                        args=[])  #outputfile
     self.thQureyOut.start()
     self.client = 'interaction'
     self.tc.AddClient(self.client)
     self.tc.troubleshooting()
     nowTime = time.time()
     self.lastCmdIssueTime = nowTime
     Cmd.__init__(self, 'tab', sys.stdin, sys.stdout)
     self.use_rawinput = True
     #import readline
     #readline.set_completer_delims('\t\n')
     #     def do_set(self,name):
     #         print(name)
     self.do_setsut(self.tc.Session.keys()[-1])
     self.helpDoc = {}
     self.cmdbank = []
Esempio n. 34
0
 def cmdloop(self):
     self.print_line(self.intro)
     while 1:
         try:
             Cmd.cmdloop(self, '')
             break
         except KeyboardInterrupt:
             self.print_line('')
     self.print_line("closing pool...")
     self.pool.close()
     # terminate all jobs
     running = 0
     for job in self.jobs:
         try:
             job.get(0)
         except multip.TimeoutError:
             running = 1
             break
     if running:
         while 1:
             yn = raw_input("Do you want wait %d running jobs? [Y/n]" % len(self.jobs)).lower()
             if yn == 'y':
                 wait = 1
                 break
             elif yn == 'n':
                 wait = 0
                 break
         if wait:
             self.print_line("waiting children...")
             self.pool.join()
             self.pool.terminate()
         else:
             self.print_line("terminate pool...")
             self.pool.terminate()
             self.pool.join()
     else:
         self.pool.terminate()
Esempio n. 35
0
    def __init__(self, mainmenu):
        Cmd.__init__(self)
        self.doc_header = "Commands"
        self.prompt = (Fore.BLUE + Style.BRIGHT + 'SS/Discovery > ' +
                       Style.RESET_ALL)
        self.description = "Discover targets on a specified network"
        self.mainmenu = mainmenu

        self.options = {
            'subnet': {
                'required':
                'True',
                'value':
                '',
                'description':
                'Subnet to discover sec products on, use CIDR or single IP',
            },
            'module': {
                'required':
                'False',
                'value':
                '',
                'description':
                'Specify specific sec prods to look for, Default is set to all',
            },
            'port': {
                'required': 'False',
                'value': '',
                'description': 'Specify ports not found in modules'
            },
            'moduleports': {
                'required': 'True',
                'value': 'true',
                'description': 'True/False: Use ports specified in modules'
            }
        }
        self.validate = sslib.Validate(self.options)
Esempio n. 36
0
    def __init__(self, controller, stdin=sys.stdin, *args, **kwargs):
        self.controller = controller
        # Local variable bindings for py command
        self.locals = {'controller': controller}
        # Attempt to handle input
        self.inPoller = poll()
        self.inPoller.register(stdin)
        Cmd.__init__(self, *args, stdin=stdin, **kwargs)

        print("Checking links and synchronizing with switches...")
        failed_links = self.check_all_links()
        if failed_links:
            formatted = ["%s-%s" % link for link in failed_links]
            print("Currently failed links:", ", ".join(formatted))
            # Notify the controller so the network will work after boot.
            self.do_notify()
        else:
            print("Currently failed links: None.")
        self.do_synchronize()

        self.hello_msg()

        self.initReadline()
        self.run()
Esempio n. 37
0
def print_menu(arr):
    global buffered
    """ Main menu printer
        @param arr is the menu array to print.  Fetches input,
        parses and built-in command keywords, and returns the selected idx.
    """

    if not buffered is None:
        # buffered input, return
        if len(buffered) > 0:
            return buffered.pop(0)
        else:
            buffered = None

    tmp = Cmd()
    arr = ['\t%s[%s%d%s] %s%s%s' % (color.B_GREEN, color.B_YELLOW, x + 1, color.B_GREEN,
        color.B_WHITE, arr[x], color.END) for x in xrange(len(arr))]
    tmp.columnize(arr, 100)
    print '\n' + color.B_YELLOW + '0' + color.B_GREEN + ')' + color.B_WHITE + ' Back' + color.END
    try:
        choice = raw_input(color.B_WHITE + '> ' + color.END)
        choice = check_opts(choice)

        # buffered input
        if choice > 1:
            choice = choice.split(' ')
            buffered = []
            for entry in choice[1:]:
                buffered.append(int(entry))
            choice = int(choice[0])
    except KeyboardInterrupt:
        choice = -1
    except Exception, e:
        debug(e)
        os.system('clear')
        choice = -1
Esempio n. 38
0
    def __init__( self, mininet, stdin=sys.stdin, script=None ):
        self.mn = mininet
        self.nodelist = self.mn.controllers + self.mn.switches + self.mn.hosts
        self.nodemap = {}  # map names to Node objects
        for node in self.nodelist:
            self.nodemap[ node.name ] = node
        # Local variable bindings for py command
        self.locals = { 'net': mininet }
        self.locals.update( self.nodemap )
        # Attempt to handle input
        self.stdin = stdin
        self.inPoller = poll()
        self.inPoller.register( stdin )
        self.inputFile = script

        self.dbmanager = DBManager()

        Cmd.__init__( self )
        info( '*** Starting CLI:\n' )

        if self.inputFile:
            self.do_source( self.inputFile )
            return
        while True:
            try:
                # Make sure no nodes are still waiting
                for node in self.nodelist:
                    while node.waiting:
                        node.sendInt()
                        node.monitor()
                if self.isatty():
                    quietRun( 'stty sane' )
                self.cmdloop()
                break
            except KeyboardInterrupt:
                output( '\nInterrupt\n' )
Esempio n. 39
0
    def __init__(self, file_input=""):
        Cmd.__init__(self)
        self.prompt = '\033[93m' + "[s1] " + '\033[0m'
        self.intro = "\nThis is the SomatoSensory SHell\n"
        self.dproj = fio.return_data_dir()
        self.server_default = self.__check_server()
        self.f_history = '.s1sh_hist_local'
        self.ddate = ''
        self.dlast = []
        self.dlist = []
        self.dsim = []
        self.expmts = []
        self.sim_list = []
        self.param_list = []
        self.var_list = []
        self.N_sims = 0

        # check to see if file_input is legit
        if os.path.isfile(file_input):
            self.file_input = file_input

        else:
            # use a default
            self.file_input = 'param/debug.param'

        # get initial count of avail processors for subprocess/multiprocessing routines
        self.nprocs = multiprocessing.cpu_count()

        # Create the initial datelist
        self.datelist = clidefs.get_subdir_list(self.dproj)

        # create the initial paramfile list
        self.__get_paramfile_list()

        # set the date, grabs a dlist
        self.do_setdate(datetime.now().strftime("%Y-%m-%d"))
Esempio n. 40
0
 def onecmd(self, line):
     try:
         if not self.blocked or line == 'EOF' or line.startswith('stage'):
             return Cmd.onecmd(self, line)
         else:
             return False
     except subprocess.CalledProcessError as e:
         log.info(on_color('RED', 'Command error: ' + str(e)))
         if self.args.exit_on_err or not self.is_interactive():
             self.abort()
     except KeyboardInterrupt as e:
         log.info(on_color('RED', '[interrupted]'))
         if self.args.exit_on_err or not self.is_interactive():
             self.last_exc = sys.exc_info()
             self.abort()
Esempio n. 41
0
 def __init__(self, options):
     options.injections = 0
     options.latent_iterations = 0
     options.compare_all = False
     options.extract_blocks = False
     if options.power_switch_outlet is not None or \
             options.power_switch_ip_address:
         switch = power_switch(options)
     else:
         switch = None
     self.drseus = fault_injector(options, switch)
     if self.drseus.db.campaign.simics:
         self.launch_simics()
     else:
         self.drseus.debugger.reset_dut()
     self.prompt = 'DrSEUs> '
     Cmd.__init__(self)
     if options.command_list:
         self.cmdqueue = options.command_list
     if exists('.supervisor_history'):
         read_history_file('.supervisor_history')
     set_history_length(options.history_length)
     if self.drseus.db.campaign.aux:
         self.__class__ = aux_supervisor
Esempio n. 42
0
    def __init__(self):
        Cmd.__init__(self)
        self.rp = RestPusher("www.foaas.com")

        "pull in FOaaS' self description"
        ret = self.rp.get("/operations")
        operation_def = ret["body"]
        """
        example from the API self description
        {"name":"Who the f**k are you anyway","url":"/anyway/:company/:from","fields":[{"name":"Company","field":"company"},{"name":"From","fie ld":"from"}]}
        """

        "generate do_<operation> functions like Cmd expects them and glue them to this class"
        for jsonNode in operation_def:
            url = jsonNode["url"]

            if "-" in url:
                continue

            url = url.replace("/", "").split(":")[0]

            fields = self.extract_fields(jsonNode)
            name = jsonNode["name"]
            self.make_method(url, name, fields)
Esempio n. 43
0
    def __init__(self, puzzle, solver, heuristic=None):
        """
        Initialize the interface.
        puzzle, solver, and heuristic are all strings giving the names of
        a puzzle in PUZZLES, a search algorithm in SOLVERS, and a valid
        heuristic for puzzle.
        """
        Cmd.__init__(self)
        self.time_limit = 30
        self.verbose = True

        self.size1 = 3
        self.size2 = 3
        if solver == "A*" and heuristic is None:
            heuristic = "manhattan distance"
        self.heuristic = heuristic
        if puzzle in self.PUZZLES:
            self.puzzle_name = self.PUZZLES[puzzle]
            self.puzzle = self.puzzle_name(size1=self.size1, size2=self.size2)

        if solver in self.SOLVERS:
            self.solver_name = self.SOLVERS[solver]
            self.new_solver()
        self.solver.set_verbose(self.verbose)
Esempio n. 44
0
    def __init__(self,
                 http_verb='get',
                 url='http://localhost/shell.php',
                 attribute='cmd',
                 ignore_certs=False,
                 headers=None,
                 data=None
                 # ,
                 # cookies=None
                 ):

        self.updatePrompt()
        self._options['http_verb'] = http_verb.lower(
        ) if http_verb != None and len(http_verb) > 0 else 'get'
        self._options['url'] = url
        self._options['attribute'] = attribute
        self._options['ignore_certs'] = ignore_certs
        self._headers = headers
        self._data = data
        # self._Cookies=cookies
        self.banner()
        Cmd.__init__(self)
        self.showOptions(None)
        self.getPwd()
Esempio n. 45
0
 def __init__(self,
              server_port='localhost:8080',
              pem_file=None,
              csv_file_dir=None):
     Cmd.__init__(self)
     self.location = ""
     self.prompt_end = '> '
     if sys.stdin.isatty():
         self.prompt = self.prompt_end
     else:
         self.prompt = ""
     self.ruler = '-'
     self.modules = OrderedDict()
     self.add_module_info(ModuleInfo("help", desc="Get help for bindctl."))
     self.server_port = server_port
     self.conn = ValidatedHTTPSConnection(self.server_port,
                                          ca_certs=pem_file)
     self.session_id = self._get_session_id()
     self.config_data = None
     if csv_file_dir is not None:
         self.csv_file_dir = csv_file_dir
     else:
         self.csv_file_dir = pwd.getpwnam(getpass.getuser()).pw_dir + \
             os.sep + '.bind10' + os.sep
Esempio n. 46
0
    def __init__(self, mininet, stdin=sys.stdin, script=None):
        """Start and run interactive or batch mode CLI
           mininet: Mininet network object
           stdin: standard input for CLI
           script: script to run in batch mode"""
        self.mn = mininet
        # Local variable bindings for py command
        self.locals = {'net': mininet}
        # Attempt to handle input
        self.stdin = stdin
        self.inPoller = poll()
        self.inPoller.register(stdin)
        self.inputFile = script
        Cmd.__init__(self)
        # Containernet allows '.' in host identifiers to build human readable hierarchical name spaces:
        self.identchars = string.ascii_letters + string.digits + '_' + '.'
        info('*** Starting CLI:\n')

        if self.inputFile:
            self.do_source(self.inputFile)
            return

        self.initReadline()
        self.run()
Esempio n. 47
0
    def __init__(self, mininet, stdin=sys.stdin, script=None):
        """Start and run interactive or batch mode CLI
           mininet: Mininet network object
           stdin: standard input for CLI
           script: script to run in batch mode"""

        self.mn = mininet
        # Local variable bindings for py command
        self.locals = { 'net': mininet }
        # Attempt to handle input
        self.stdin = stdin
        self.inPoller = poll()
        self.inPoller.register(stdin)
        self.inputFile = script

        Cmd.__init__(self)
        info('*** Starting CLI:\n')

        if self.inputFile:
            self.do_source(self.inputFile)
            return

        self.initReadline()
        self.run()
Esempio n. 48
0
 def postcmd(self, stop, line):
     ####################################################################
     """Fix command line arguments, this is a hack to allow argparse
     function as we expect"""
     ####################################################################
     if str(line) == "edit" or "--no-cache" in line:
         self._reload_config()
     elif str(line.split()[0]) in [
             "create",
             "delete",
             "import",
             "generate",
             "rename",
     ]:
         self._load_pwdb()
     return Cmd.postcmd(self, stop, line)
Esempio n. 49
0
    def onecmd(self, line):
        '''Modified Cmd.cmd.onecmd so that it can detect if a file is a script,
        and can run it appropriately

        Keyword arguments:
        line - string.  Is what the user enters at the terminal

        Check if value entered is a shell script
        '''

        is_script, script = get_script_cmd(line, self.real_path)
        if is_script:
            # TODO: what is this?
            self.do_shell(line)
        else:
            self.last_cmd_output = Cmd.onecmd(self, line)
            return self.last_cmd_output
Esempio n. 50
0
    def get_ig_ips(self, ig):
        task = "Get Instancegroup IPS"
        cmd = 'kubectl get nodes -o wide --show-labels | grep "instancegroup={0}" | cut -d" " -f1'.format(
            ig)
        #        print cmd
        result = Cmd.local_run_get_out_raw(task, cmd)
        outlist = []
        for line in result.split("\n"):
            if line:
                line = line.split(
                    '-'
                )  # highly dependant on hostname not being changed from amazon default. find better way fast (example: 'ip-172-32-56-155.ec2.internal')
                outlist.append('{0}.{1}.{2}.{3}'.format(
                    line[1], line[2], line[3], line[4].split('.')[0]))

        #       print outlist
        return outlist
Esempio n. 51
0
 def onecmd(self, line):
     """This method is subclassed just to be
     able to encapsulate it with a try/except bloc"""
     try:
         # Decode user input
         line = line
         return Cmd.onecmd(self, line)
     except YokadiOptionParserNormalExitException:
         pass
     except UnicodeDecodeError as e:
         tui.error(
             "Unicode decoding error. Please check you locale and terminal settings (%s)."
             % e)
     except UnicodeEncodeError as e:
         tui.error(
             "Unicode encoding error. Please check you locale and terminal settings (%s)."
             % e)
     except BadUsageException as e:
         tui.error("*** Bad usage ***\n\t%s" % e)
         cmd = line.split(' ')[0]
         self.do_help(cmd)
     except YokadiException as e:
         tui.error("*** Yokadi error ***\n\t%s" % e)
     except IOError as e:
         # We can get I/O errors when yokadi is piped onto another shell commands
         # that breaks.
         print("*** I/O error ***\n\t%s" % e, file=sys.stderr)
     except KeyboardInterrupt:
         print("*** Break ***")
     except Exception as e:
         tui.error("Unhandled exception (oups)\n\t%s" % e)
         print("This is a bug of Yokadi, sorry.")
         print(
             "Send the above message by email to Yokadi developers ([email protected]) to help them make"
             " Yokadi better.")
         cut = "---------------------8<----------------------------------------------"
         print(cut)
         traceback.print_exc()
         print("--")
         print("Python: %s" % sys.version.replace("\n", " "))
         print("SQL Alchemy: %s" % sqlalchemy.__version__)
         print("OS: %s (%s)" % os.uname()[0:3:2])
         print("Yokadi: %s" % yokadi.__version__)
         print(cut)
         print()
Esempio n. 52
0
    def do_help(self, line):
        """I think you know what this does."""
        # this works around a misfeature in cmd.py
        # getdoc is better at docs than the raw (cleans them up)
        line = line.strip()
        try:
            if line and not getattr(self, 'help_' + line, None):
                from pydoc import getdoc
                docs = getdoc(getattr(self, 'do_' + line))
                if not docs:
                    docs = '(to be documented)'
                self.stdout.write("%s: %s\n" %
                                  (ansi.BOLD + line + ansi.RESET, str(docs)))
                return
        except:
            pass

        return Cmd.do_help(self, line)
Esempio n. 53
0
    def do_help(self, arg):
        '''List available commands with 'help' or detailed help with
        'help cmd'.

        '''
        if not arg:
            return Cmd.do_help(self, arg)
        arg = arg.replace('-', '_')
        try:
            doc = getattr(self, 'do_' + arg).__doc__
            if doc:
                doc = doc.format(command=arg)
                self.stdout.write('%s\n' % trim(str(doc)))
                return
        except AttributeError:
            pass
        self.stdout.write('%s\n' % str(self.nohelp % (arg, )))
        return
Esempio n. 54
0
    def parseline(self, line):
        """
        This REPL method is overridden to search "short" alias of commands
        """
        cmd, arg, ignored = Cmd.parseline(self, line)

        if cmd is not None:
            names = set(name for name in self.get_names()
                        if name.startswith('do_'))

            if 'do_' + cmd not in names:
                long = set(name for name in names
                           if name.startswith('do_' + cmd))
                # if more than one result, ambiguous command, do nothing (error will display suggestions)
                if len(long) == 1:
                    cmd = long.pop()[3:]

        return cmd, arg, ignored
Esempio n. 55
0
class Console(Cmd):
    ''' command line tool to control a cloud cluster '''

    dustintro = "Dust cluster shell, version %s. Type %s?%s for help." % (
        __version__, colorama.Fore.GREEN, colorama.Style.RESET_ALL)

    def __init__(self):

        util.intro()

        logger.setLevel(logging.INFO)

        # read/create config
        try:
            self.config = DustConfig()
        except Exception, e:
            logger.error("Error getting config/credentials. Cannot continue.")
            raise

        # load history
        try:
            if os.path.exists(self.config.get_history_file_path()):
                readline.read_history_file(self.config.get_history_file_path())

        except IOError:
            logger.warning(
                "Error reading history file. No command history available.")

        atexit.register(self.on_exit, None)

        Cmd.__init__(self)

        self.commands = {}  # { cmd : (helpstr, module) }
        # startup
        self.cluster = ClusterCommandEngine()

        self.exit_flag = False
        self.cluster.lineterm.set_refresh_callback(self.redisplay)

        threading.Thread(target=self.cluster.load_commands).start()
        logger.info(self.dustintro)
Esempio n. 56
0
    def do_help(self, line):
        if line:
            return Cmd.do_help(self, line)

        self.basecmds.sort()
        self.vprint('\nbasics:')

        for line in formatargs(self.basecmds):
            self.vprint(line)

        subsys = self.extsubsys.keys()
        subsys.sort()

        for sub in subsys:
            self.vprint('\n%s:' % sub)
            cmds = self.extsubsys.get(sub)
            cmds.sort()
            for line in formatargs(cmds):
                self.vprint(line)

        self.vprint('\n')
Esempio n. 57
0
 def parseline(self, line):
     """Parse the line into a command name and a string containing
     the arguments.  Returns a tuple containing (command, args, line).
     'command' and 'args' may be None if the line couldn't be parsed.
     """
     line = line.strip()
     if not line:
         ret = (None, None, line)
         #return None, None, line
     else:
         # If the line starts with "!" execute as a system cmd
         if line.startswith('!'):
             line = 'sh {0}'.format(line.lstrip("!"))
         # If the line starts with a "?" execute as a help cmd
         elif '?' in line:
             if line[0] == '?':
                 if len(line) == 1:
                     return 'menu_summary', '', line
             elif len(line.split()) == 1:
                 line = 'help ' + str(line).replace('?', '')
         ret = Cmd.parseline(self, line)
     return ret
Esempio n. 58
0
File: cli.py Progetto: wflk/vivisect
    def do_help(self, line):
        if line:
            return Cmd.do_help(self, line)

        self.basecmds.sort()
        self.vprint('\nbasics:')

        #self.vprint( self.columnize( self.basecmds ) )
        self.columnize(self.basecmds)

        subsys = self.extsubsys.keys()
        subsys.sort()

        for sub in subsys:
            self.vprint('\n%s:' % sub)

            cmds = self.extsubsys.get(sub)
            cmds.sort()

            self.columnize(cmds)

        self.vprint('\n')
Esempio n. 59
0
    def precmd(self, line):
        current_dir = os.getcwd()  # 获取check_tool的目录
        result_dir = os.path.join(current_dir, "check_result/")
        config_dir = os.path.join(current_dir, "check_config/")
        # 方式exit命令重新打开文件,刷空文件,在输入如下3种命令和空行命令时,可以处理文件
        if (line.strip() in ["check all", "check c", "check h", ""]):
            self.log_f = open(result_dir + "annotation_check_logs.log", "w")
            self.w_f = open(result_dir + "annotation_check_results.log", "w")
            self.fail_f = open(result_dir + "annotation_fail_files.log", "w")
            self.ignore_f = open(config_dir + "ignore_file_list.log", "r")
            print(" "*15 +"annotation rate threshold:%.2f%%,the following files are the unqualified files" \
                    %self.rate,file=self.fail_f)
            print(
                "---------------------------------------------unqualified files list-------------------------------------------------- ",
                file=self.fail_f)
            print("注:若文件头部注释区域无author定义,owner 显示为文件名\n", file=self.fail_f)

        if (line.strip() == ""):
            test_cmd_color.printGreen(
                "the command is empty, will execute the last nonempty command\n\n"
            )
        return Cmd.precmd(self, line)
Esempio n. 60
0
 def run(self, reads):
     """ Run the Hisat2 mapping with the given reads. """
     logger.debug("Perform Hisat2 mapping.")
     if len(reads) == 1:  # single end reads
         hisat = Cmd(
             f"hisat2 -q --threads {self.threads} -k 1 -x {self.index_name} -U {reads[0]} --no-unal | \
                     samtools view --threads {self.threads} -hS -F 4 -q 1 -O SAM"
         )
     elif len(reads) == 2:  # paired end reads
         hisat = Cmd(
             f"hisat2 -q --threads {self.threads} -k 1 -x {self.index_name} -1 {reads[0]} -2 {reads[1]} --no-unal | \
                         samtools view --threads {self.threads} -hS -F 4 -q 1 -O SAM"
         )
     hisat.run()
     self.mapping_has_run = True
     return (entry for entry in hisat.stdout.split("\n")[:-1]
             if not entry.startswith("@"))