def _controlServer(argv):
    timeout = PshellServer._gPshellClientTimeout
    if PshellServer._gClientTimeoutOverride:
        if len(PshellServer._gClientTimeoutOverride) > 2:
            timeout = int(PshellServer._gClientTimeoutOverride[2:])
    server = _getServer(argv[0])
    if (server != None):
        # see if they asked for help
        if ((len(argv) == 1) or (argv[1] == "help") or (argv[1] == "-h")
                or (argv[1] == "-help") or (argv[1] == "--h")
                or (argv[1] == "--help") or (argv[1] == "?")):
            # user asked for help, display all the registered commands of the remote server
            PshellServer.printf(PshellControl.extractCommands(server["sid"]),
                                newline=False)
        elif timeout == 0:
            print(
                "PSHELL_INFO: Command sent fire-and-forget, no response requested"
            )
            PshellControl.sendCommand1(server["sid"], ' '.join(argv[1:]))
        else:
            # reconstitute and dispatch original command to remote server minus the first keyword
            (results,
             retCode) = PshellControl.sendCommand4(server["sid"], timeout,
                                                   ' '.join(argv[1:]))
            # good return, display results back to user
            if (retCode == PshellControl.COMMAND_SUCCESS):
                PshellServer.printf(results, newline=False)
def controlServer(sid, argv):
    # reconstitute the original command
    command = ' '.join(argv)
    if ((len(argv) == 0) or PshellServer.isHelp() or (argv[0] == "help")):
        PshellServer.printf(PshellControl.extractCommands(sid))
    else:
        (results, retCode) = PshellControl.sendCommand3(sid, command)
        if (retCode == PshellControl.COMMAND_SUCCESS):
            PshellServer.printf(results, newline=False)
def meta(argv):
    global pshellServerDemoSid
    global traceFilterDemoSid
    (results,
     retCode) = PshellControl.sendCommand3(pshellServerDemoSid,
                                           "hello %s %s" % (argv[0], argv[1]))
    if (retCode == PshellControl.COMMAND_SUCCESS):
        PshellServer.printf(results, newline=False)

    PshellControl.sendCommand1(traceFilterDemoSid, "set callback %s" % argv[2])
def enhancedUsage(argv):
    # see if the user asked for help
    if (PshellServer.isHelp()):
        # show standard usage
        PshellServer.showUsage()
        # give some enhanced usage
        PshellServer.printf("Enhanced usage here...")
    else:
        # do normal function processing
        PshellServer.printf("enhancedUsage command dispatched:")
        for index, arg in enumerate(argv):
            PshellServer.printf("  argv[%d]: '%s'" % (index, arg))
Exemple #5
0
def _comandDispatcher(args_):
    global _gSid
    global _gHelp
    global _gInteractive
    global _gTimeout
    results = None
    timeout = PshellServer._gPshellClientTimeout
    if PshellServer._gClientTimeoutOverride:
        if len(PshellServer._gClientTimeoutOverride) > 2:
            timeout = int(PshellServer._gClientTimeoutOverride[2:])
    command = ' '.join(args_)
    if args_[0] in _gHelp:
        results = PshellControl.extractCommands(_gSid, includeName=False)
    elif timeout == 0:
        # if they asked for command help, go ahead and dispatch the command and
        # extract the results, otherwise, just send command with no extraction
        # or display
        if len(args_) == 2 and args_[1] in _gHelp:
            (results,
             retCode) = PshellControl.sendCommand4(_gSid,
                                                   PshellControl.ONE_SEC * 5,
                                                   command)
        else:
            print(
                "PSHELL_INFO: Command sent fire-and-forget, no response requested"
            )
            PshellControl.sendCommand1(_gSid, command)
    else:
        (results,
         retCode) = PshellControl.sendCommand4(_gSid, timeout, command)
    if results != None:
        if _gInteractive == True:
            PshellServer.printf(results, newline=False)
        else:
            # command line mode
            sys.stdout.write(results)
def _cleanupAndExit():
    PshellServer.cleanupResources()
    PshellControl.disconnectAllServers()
    sys.exit()
def _multicast(argv):
    if (PshellServer.isHelp()):
        PshellServer.printf()
        PshellServer.showUsage()
        PshellServer.printf()
        PshellServer.printf(
            "  Send a registered multicast command to the associated")
        PshellServer.printf("  multicast remote server group")
        _show(('show', 'multicast'))
    else:
        # reconstitute the original command
        PshellControl.sendMulticast(' '.join(argv[1:]))
def _show(argv):
    global _gPshellServers
    global _gMaxLocalName
    global _gMaxRemoteName
    global _gMulticast
    global _gMaxMulticastKeyword
    global _gRemoteNameLabel
    global _gLocalNameLabel
    global _gKeywordLabel
    if (PshellServer.isSubString(argv[1], "server")):
        PshellServer.printf()
        PshellServer.printf(
            "*************************************************")
        PshellServer.printf(
            "*           AGGREGATED REMOTE SERVERS           *")
        PshellServer.printf(
            "*************************************************")
        PshellServer.printf()
        PshellServer.printf("%s    %s    Port" %
                            (_gLocalNameLabel.ljust(_gMaxLocalName),
                             _gRemoteNameLabel.ljust(_gMaxRemoteName)))
        PshellServer.printf(
            "%s    %s    ======" %
            ("=".ljust(_gMaxLocalName, "="), "=".ljust(_gMaxRemoteName, "=")))
        for server in _gPshellServers:
            PshellServer.printf("%s    %s    %s" %
                                (server["localName"].ljust(_gMaxLocalName),
                                 server["remoteServer"].ljust(_gMaxRemoteName),
                                 server["port"]))
        PshellServer.printf()
    elif (PshellServer.isSubString(argv[1], "multicast")):
        PshellServer.printf()
        PshellServer.printf(
            "*****************************************************")
        PshellServer.printf(
            "*            REGISTERED MULTICAST GROUPS            *")
        PshellServer.printf(
            "*****************************************************")
        PshellServer.printf()
        PshellServer.printf("%s    %s    %s    Port" %
                            (_gKeywordLabel.ljust(_gMaxMulticastKeyword),
                             _gLocalNameLabel.ljust(_gMaxLocalName),
                             _gRemoteNameLabel.ljust(_gMaxRemoteName)))
        PshellServer.printf(
            "%s    %s    %s    ======" %
            ("=".ljust(_gMaxMulticastKeyword, "="), "=".ljust(
                _gMaxLocalName, "="), "=".ljust(_gMaxRemoteName, "=")))
        for multicast in _gMulticast:
            PshellServer.printf(
                "%s    " % multicast["keyword"].ljust(_gMaxMulticastKeyword),
                newline=False)
            for index, server in enumerate(multicast["servers"]):
                if (index > 0):
                    PshellServer.printf("%s    " %
                                        " ".ljust(_gMaxMulticastKeyword, " "),
                                        newline=False)
                PshellServer.printf(
                    "%s    %s    %s" %
                    (server["localName"].ljust(_gMaxLocalName),
                     server["remoteServer"].ljust(_gMaxRemoteName),
                     server["port"]))
        PshellServer.printf()
    else:
        PshellServer.showUsage()
def _add(argv):
    global _gPshellServers
    global _gMaxLocalName
    global _gMaxRemoteName
    global _gMulticast
    global _gMaxMulticastKeyword
    global _gRemoteNameLabel
    global _gLocalNameLabel
    global _gKeywordLabel
    if (PshellServer.isHelp()):
        PshellServer.printf()
        PshellServer.showUsage()
        PshellServer.printf()
        PshellServer.printf("  where:")
        PshellServer.printf(
            "    <localName>    - Local logical name of the server, must be unique"
        )
        PshellServer.printf(
            "    <remoteServer> - Hostname or IP address of UDP server or name of UNIX server"
        )
        PshellServer.printf(
            "    <port>         - UDP port number or 'unix' for UNIX server (can be omitted for UNIX)"
        )
        PshellServer.printf(
            "    <keyword>      - Multicast group keyword, must be valid registered remote command"
        )
        PshellServer.printf()
    elif (PshellServer.isSubString(argv[1], "server")):
        # default port
        port = PshellServer.UNIX
        if (len(argv) == 5):
            port = argv[4]
        if (not _isDuplicate(argv[2], argv[3], port)):
            if (len(argv[2]) > _gMaxLocalName):
                _gMaxLocalName = max(len(argv[2]), len(_gLocalNameLabel))
            if (len(argv[3]) > _gMaxRemoteName):
                _gMaxRemoteName = max(len(argv[3]), len(_gRemoteNameLabel))
            _gPshellServers.append({
                "localName":
                argv[2],
                "remoteServer":
                argv[3],
                "port":
                port,
                "sid":
                PshellControl.connectServer(argv[2], argv[3], port,
                                            PshellControl.ONE_SEC * 5)
            })
            PshellServer.addCommand(
                _controlServer, argv[2],
                "control the remote " + argv[2] + " process",
                "[<command> | ? | -h]", 0, 30, False)
            PshellServer._addTabCompletions()
        else:
            PshellServer.printf(
                "ERROR: Local name: %s, remote server: %s, port: %s already exists"
                % (argv[2], argv[3], argv[4]))
    elif (PshellServer.isSubString(argv[1], "multicast")):
        multicast = _getMulticast(argv[2])
        if (multicast == None):
            # new keyword
            if (len(argv[2]) > _gMaxMulticastKeyword):
                _gMaxMulticastKeyword = max(len(argv[2]), len(_gKeywordLabel))
            _gMulticast.append({"keyword": argv[2], "servers": []})
            multicast = _gMulticast[-1]
        # add servers to this keyword
        for localName in argv[3:]:
            server = _getServer(localName)
            if (server != None):
                PshellControl.addMulticast(server["sid"], argv[2])
                multicast["servers"].append(server)
    else:
        PshellServer.showUsage()
            "  can also create multicast groups for sets of remote servers.  The remote"
        )
        print(
            "  servers and multicast groups can be added interactively via the 'add'"
        )
        print(
            "  command or at startup via the 'pshellAggregator.startup' file.")
        print("")
        exit(0)

    # make sure we cleanup any system resorces on an abnormal termination
    _registerSignalHandlers()

    # need to set the first arg position to 0 so we can pass
    # through the exact command to our remote server for dispatching
    PshellServer._setFirstArgPos(0)

    # we tell the local server we are the special UDP/UNIX command
    # line client so it can process commands correctly and display
    # the correct banner  information
    PshellServer._gPshellClient = True

    # supress the automatic invalid arg count message from the PshellControl.py
    # module so we can display the returned usage
    PshellControl._gSupressInvalidArgCountMessage = True

    # register our callback commands
    PshellServer.addCommand(
        _add, "add", "add a new remote server or multicast group entry",
        "{server <localName> <remoteServer> [<port>]} | {multicast <keyword> <localName1> [<localName2>...<localNameN>]}",
        4, 30, False)
        elif (sys.argv[1] == "-local"):
            serverType = PshellServer.LOCAL
        else:
            showUsage()
        if len(sys.argv) == 3:
            PSHELL_DEMO_PORT = int(sys.argv[2])
    else:
        showUsage()

    # register signal handlers so we can do a graceful termination and cleanup any system resources
    registerSignalHandlers()

    # register our callback commands, commands consist of single keyword only
    PshellServer.addCommand(function=helloWorld,
                            command="helloWorld",
                            description="command that prints out arguments",
                            usage="[<arg1> ... <arg20>]",
                            minArgs=0,
                            maxArgs=20)

    # TCP or LOCAL servers don't need a keep-alive, so only add
    # this command for connectionless datagram type servers
    if ((serverType == PshellServer.UDP) or (serverType == PshellServer.UNIX)):
        PshellServer.addCommand(
            function=keepAlive,
            command="keepAlive",
            description="command to show client keep-alive ('C' client only)",
            usage="dots | bang | pound | wheel",
            minArgs=1,
            showUsage=False)

    PshellServer.addCommand(
def wildcardMatch(argv):
    if (PshellServer.isHelp()):
        PshellServer.printf()
        PshellServer.showUsage()
        PshellServer.printf()
        PshellServer.printf("  where valid <args> are:")
        PshellServer.printf("    on")
        PshellServer.printf("    of*f")
        PshellServer.printf("    a*ll")
        PshellServer.printf("    sy*mbols")
        PshellServer.printf("    se*ttings")
        PshellServer.printf("    d*efault")
        PshellServer.printf()
    elif (PshellServer.isSubString(argv[0], "on", 2)):
        PshellServer.printf("argv 'on' match")
    elif (PshellServer.isSubString(argv[0], "off", 2)):
        PshellServer.printf("argv 'off' match")
    elif (PshellServer.isSubString(argv[0], "all", 1)):
        PshellServer.printf("argv 'all' match")
    elif (PshellServer.isSubString(argv[0], "symbols", 2)):
        PshellServer.printf("argv 'symbols' match")
    elif (PshellServer.isSubString(argv[0], "settings", 2)):
        PshellServer.printf("argv 'settings' match")
    elif (PshellServer.isSubString(argv[0], "default", 1)):
        PshellServer.printf("argv 'default' match")
    else:
        PshellServer.printf()
        PshellServer.showUsage()
        PshellServer.printf()
        PshellServer.printf("  where valid <args> are:")
        PshellServer.printf("    on")
        PshellServer.printf("    of*f")
        PshellServer.printf("    a*ll")
        PshellServer.printf("    sy*mbols")
        PshellServer.printf("    se*ttings")
        PshellServer.printf("    d*efault")
        PshellServer.printf()
    traceFilterDemoSid = PshellControl.connectServer("traceFilterDemo",
                                                     sys.argv[1],
                                                     traceFilterDemoPort,
                                                     PshellControl.ONE_SEC * 5)

    # add some multicast groups for our control sids, a multicast group is based
    # on the command's keyword
    PshellControl.addMulticast(pshellServerDemoSid, "trace")
    PshellControl.addMulticast(traceFilterDemoSid, "trace")

    PshellControl.addMulticast(pshellServerDemoSid, "test")
    PshellControl.addMulticast(traceFilterDemoSid, "test")

    # register our callback commands
    PshellServer.addCommand(pshellServerDemo, "pshellServerDemo",
                            "control the remote pshellServerDemo process",
                            "[<command> | ? | -h]", 0, 30, False)

    PshellServer.addCommand(traceFilterDemo, "traceFilterDemo",
                            "control the remote traceFilterDemo process",
                            "[<command> | ? | -h]", 0, 30, False)

    # add any "meta" commands here, meta commands can aggregate multiple discrete
    # pshell commands, either within one server or across multiple servers, into
    # one command
    PshellServer.addCommand(meta, "meta",
                            "meta command, wraps multiple seperate functions",
                            "<arg1> <arg2> <arg3>", 3, 3)

    # add an example command that uses the one-to-many multicast feature of
    # the control API
def _getServer(localName):
    global _gPshellServers
    for server in _gPshellServers:
        if (PshellServer.isSubString(localName, server["localName"])):
            return (server)
    return (None)
def helloWorld(argv):
    PshellServer.printf("helloWorld command dispatched:")
    for index, arg in enumerate(argv):
        PshellServer.printf("  argv[%d]: '%s'" % (index, arg))
def signalHandler(signal, frame):
    PshellServer.cleanupResources()
    print("")
    sys.exit()
def getOptions(argv):
    if (PshellServer.isHelp()):
        PshellServer.printf()
        PshellServer.showUsage()
        PshellServer.printf()
        PshellServer.printf("  where:")
        PshellServer.printf(
            "    arg - agrument of the format -<key><value> or <key>=<value>")
        PshellServer.printf()
        PshellServer.printf(
            "  For the first form, the <key> must be a single character, e.g. -t10"
        )
        PshellServer.printf(
            "  for the second form, <key> can be any length, e.g. timeout=10")
        PshellServer.printf()
    else:
        for index, arg in enumerate(argv):
            (parsed, key, value) = PshellServer.getOption(arg)
            PshellServer.printf(
                "arg[%d]: '%s', parsed: %s, key: '%s', value: '%s'" %
                (index, arg, parsed, key, value))
def advancedParsing(argv):

    numTokens, timestamp = PshellServer.tokenize(argv[0], ":")

    if (numTokens != 6):
        PshellServer.printf("ERROR: Improper timestamp format!!")
        PshellServer.showUsage()
    elif (not PshellServer.isDec(timestamp[0])
          or PshellServer.getInt(timestamp[0]) > MAX_YEAR):
        PshellServer.printf(
            "ERROR: Invalid year: %s, must be numeric value <= %d" %
            (timestamp[0], MAX_YEAR))
    elif (not PshellServer.isDec(timestamp[1])
          or PshellServer.getInt(timestamp[1]) > MAX_MONTH):
        PshellServer.printf(
            "ERROR: Invalid month: %s, must be numeric value <= %d" %
            (timestamp[1], MAX_MONTH))
    elif (not PshellServer.isDec(timestamp[2])
          or PshellServer.getInt(timestamp[2]) > MAX_DAY):
        PshellServer.printf(
            "ERROR: Invalid day: %s, must be numeric value <= %d" %
            (timestamp[2], MAX_DAY))
    elif (not PshellServer.isDec(timestamp[3])
          or PshellServer.getInt(timestamp[3]) > MAX_HOUR):
        PshellServer.printf(
            "ERROR: Invalid hour: %s, must be numeric value <= %d" %
            (timestamp[3], MAX_HOUR))
    elif (not PshellServer.isDec(timestamp[4])
          or PshellServer.getInt(timestamp[4]) > MAX_MINUTE):
        PshellServer.printf(
            "ERROR: Invalid minute: %s, must be numeric value <= %d" %
            (timestamp[4], MAX_MINUTE))
    elif (not PshellServer.isDec(timestamp[5])
          or PshellServer.getInt(timestamp[5]) > MAX_SECOND):
        PshellServer.printf(
            "ERROR: Invalid second: %s, must be numeric value <= %d" %
            (timestamp[5], MAX_SECOND))
    else:
        PshellServer.printf("Year   : %s" % timestamp[0])
        PshellServer.printf("Month  : %s" % timestamp[1])
        PshellServer.printf("Day    : %s" % timestamp[2])
        PshellServer.printf("Hour   : %s" % timestamp[3])
        PshellServer.printf("Minute : %s" % timestamp[4])
        PshellServer.printf("Second : %s" % timestamp[5])
def keepAlive(argv):
    if (PshellServer.isHelp()):
        PshellServer.printf()
        PshellServer.showUsage()
        PshellServer.printf()
        PshellServer.printf(
            "Note, this function demonstrates intermediate flushes in a")
        PshellServer.printf(
            "callback command to keep the UDP/UNIX interactive client from")
        PshellServer.printf(
            "timing out for commands that take longer than the response")
        PshellServer.printf(
            "timeout (default=5 sec).  This is only supported in the 'C'")
        PshellServer.printf(
            "version of the pshell interactive client, the Python version")
        PshellServer.printf(
            "of the interactive client does not support intermediate flushes.")
        PshellServer.printf()
        return
    elif (argv[0] == "dots"):
        PshellServer.printf("marching dots keep alive:")
        for i in range(1, 10):
            PshellServer.march(".")
            time.sleep(1)
    elif (argv[0] == "bang"):
        PshellServer.printf("marching 'bang' keep alive:")
        for i in range(1, 10):
            PshellServer.march("!")
            time.sleep(1)
    elif (argv[0] == "pound"):
        PshellServer.printf("marching pound keep alive:")
        for i in range(1, 10):
            PshellServer.march("#")
            time.sleep(1)
    elif (argv[0] == "wheel"):
        PshellServer.printf("spinning wheel keep alive:")
        for i in range(1, 10):
            # string is optional, use NULL to omit
            PshellServer.wheel("optional string: ")
            time.sleep(1)
    else:
        PshellServer.showUsage()
        return
    PshellServer.printf()
def formatChecking(argv):
    PshellServer.printf("formatChecking command dispatched:")
    if PshellServer.isIpv4Addr(argv[0]):
        PshellServer.printf("IPv4 address entered: '%s' entered" % argv[0])
    elif PshellServer.isIpv4AddrWithNetmask(argv[0]):
        PshellServer.printf("IPv4 address/netmask entered: '%s' entered" %
                            argv[0])
    elif PshellServer.isDec(argv[0]):
        PshellServer.printf("Decimal arg: %d entered" %
                            PshellServer.getInt(argv[0]))
    elif PshellServer.isHex(argv[0]):
        PshellServer.printf("Hex arg: 0x%x entered" %
                            PshellServer.getInt(argv[0]))
    elif PshellServer.isAlpha(argv[0]):
        if PshellServer.isEqual(argv[0], "myarg"):
            PshellServer.printf("Alphabetic arg: '%s' equal to 'myarg'" %
                                argv[0])
        else:
            PshellServer.printf("Alphabetic arg: '%s' not equal to 'myarg'" %
                                argv[0])
    elif PshellServer.isAlphaNumeric(argv[0]):
        if PshellServer.isEqual(argv[0], "myarg1"):
            PshellServer.printf("Alpha numeric arg: '%s' equal to 'myarg1'" %
                                argv[0])
        else:
            PshellServer.printf(
                "Alpha numeric arg: '%s' not equal to 'myarg1'" % argv[0])
    elif PshellServer.isFloat(argv[0]):
        PshellServer.printf("Float arg: %.2f entered" %
                            PshellServer.getFloat(argv[0]))
    else:
        PshellServer.printf("Unknown arg format: '%s'" % argv[0])
Exemple #21
0
        _gInteractive = True

        if (_gIsBroadcastAddr == False):

            # if not a broadcast server address, extract all the commands from
            # our unicast remote server and add them to our local server
            commandList = PshellControl.extractCommands(_gSid)
            if (len(commandList) > 0):
                commandList = commandList.split("\n")
                for command in commandList:
                    splitCommand = command.split("-")
                    if (len(splitCommand) >= 2):
                        commandName = splitCommand[0].strip()
                        description = splitCommand[1].strip()
                        PshellServer.addCommand(_comandDispatcher, commandName,
                                                description,
                                                "[<arg1> ... <arg20>]", 0, 20)

                # configure our local server to interact with a remote server, we override the display settings
                # (i.e. prompt, server name, banner, title etc), to make it appear that our local server is really
                # a remote server

                _configureLocalServer()

                # now start our local server which will interact with a remote server via the pshell control machanism
                PshellServer.startServer("pshellServer", PshellServer.LOCAL,
                                         PshellServer.BLOCKING)
            else:
                print("PSHELL_ERROR: Could not connect to server: '%s:%s'" %
                      (_gRemoteServer, _gPort))