def getProcToPortDictOnAIX(localClient, USE_SUDO, USE_LSOF):
    try:
        dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX]')
        procToPortDict = {}

        ## Get process OSHs
        ############################################
        try:
            psOut = localClient.executeCmd("ps -e -o 'user,pid,time,args'")
            psLines = dbconnect_utils.splitCommandOutput(psOut.strip())
            if psLines == None:
                logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Unable to get list of processes!')
                return None
            for psLine in psLines:
                if(re.search('TIME COMMAND', psLine)):
                    continue
                ## Reg for processes with args
                res = re.search('(\w+)\s+?(\d+).*:\d\d\s([0-9a-zA-Z_.\[\]\-+:/]+)\s(.*)', psLine)
                if(res):
                    cleanArgs = res.group(4)
                else:
                ## Reg for processes with no args
                    res = re.search('(\w+)\s+?(\d+).*:\d\d\s([0-9a-zA-Z_.\[\]\-+:/]+)', psLine)
                    if(res):
                        cleanArgs = ''
                if(res):
                    commandPath = res.group(3)
                    pid = res.group(2)
                    userName = res.group(1)
                    cleanCommand = ''
                    if commandPath.find('/') == -1:
                        cleanCommand = commandPath
                    else:
                        res2 = re.search('(.*/)([^/]+)', commandPath)
                        if (res2):
                            cleanCommand = res2.group(2)
                        else:
                            continue
                    commandLine = cleanCommand + ' ' + cleanArgs
                    dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Got PROCESS <%s:%s> with path <%s>, owner <%s>, and command line <%s>' % (pid, cleanCommand, commandPath, userName, commandLine))
                    if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine, userName) == 0:
                        logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s>, owner <%s>, and command line <%s> to the procToPort dictionary' % (pid, cleanCommand, 'Running', commandPath, userName, commandLine))
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Unable to get list of processes: <%s>' % excInfo)
            pass

        if USE_LSOF.lower().strip() == 'true':
            ## Use LSOF to map each process to a port and create a dictionary
            ############################################
            try:
                keydeletion = [] # keys to delete - Daniel La
                pidToPortMap = {} ## We need a local pid to port map
                # lsofCmd = 'lsof -n -P -i | grep -i listen 2>/dev/null'
                lsofCmd = '/usr/local/bin/lsof -n -P -i | grep -i listen 2>/dev/null' # Daniel La need to specify full path to lsof. 22/11/10
                if USE_SUDO == 'true':
                    lsofCmd = 'sudo ' + lsofCmd
                lsofStr = localClient.executeCmd(lsofCmd)
                lsofLines = dbconnect_utils.splitCommandOutput(lsofStr.strip())
                if lsofLines != None:
                    for lsofLine in lsofLines:
                        if len(lsofLine) <1:
                            continue
                        lsofLine = lsofLine.strip()
                        m = re.search('\w+\s+(\d+)\s+\w+\s+\w+\s+IPv[4|6].+TCP\s+(\S+):(\d+)\s+\(\w+\)', lsofLine)
                        if (m):
                            pid = m.group(1).strip()
                            ipAddress = m.group(2).strip()
                            ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                            ipAddress = dbconnect_utils.fixIP(ipAddress, localClient.getIpAddress())
                            serverPort = m.group(3).strip()
                            # pidToPortMap[pid] = [ipAddress, serverPort]
                            # below lines were added - Daniel La
                            logger.debug('serverport is: ', serverPort, ',pid is: ', pid, ',ip is: ', ipAddress)
                            pidnport = str(pid) + '.' + str(serverPort)
                            pidToPortMap[pidnport] = [ipAddress, serverPort]
                            # end of add.
                    if pidToPortMap != None and len(pidToPortMap) > 0:
                        for pid in pidToPortMap.keys():
                            logger.debug('before pid is: ', pid)
                            m = re.search('(\w+)\.\w+', pid)
                            pidsplit = m.group(1).strip()
                            logger.debug('after found pid is: ', pidsplit)
                            # if pid in procToPortDict.keys():
                            if pidsplit in procToPortDict.keys():
                                ipAddress = (pidToPortMap[pid])[0]
                                ## Skip loopback IPs
                                if re.search('127.0.0', ipAddress):
                                    continue
                                serverPort = (pidToPortMap[pid])[1]
                                #dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Found port <%s:%s> for pid <%s>' % (ipAddress, serverPort, pid))
                                #(procToPortDict[pid])[dbconnect_utils.IP_INDEX] = ipAddress
                                #(procToPortDict[pid])[dbconnect_utils.PORT_INDEX] = serverPort
                                dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Found port <%s:%s> for pid <%s>' % (ipAddress, serverPort, pidsplit))
                                (procToPortDict[pidsplit])[dbconnect_utils.IP_INDEX] = ipAddress
                                (procToPortDict[pidsplit])[dbconnect_utils.PORT_INDEX] = serverPort

                                # create new key and add new entry - Daniel La
                                logger.debug('creating new entry for: ', (procToPortDict[pidsplit])[dbconnect_utils.PROCESSNAME_INDEX], ' pid: ', pidsplit, ' port: ', serverPort)
                                pidnport = str(pidsplit) + '.' + str(serverPort)
                                if dbconnect_utils.populateProcToPortDict(procToPortDict, pidnport, (procToPortDict[pidsplit])[dbconnect_utils.PROCESSNAME_INDEX], (procToPortDict[pidsplit])[dbconnect_utils.PORT_INDEX], (procToPortDict[pidsplit])[dbconnect_utils.IP_INDEX], (procToPortDict[pidsplit])[dbconnect_utils.PATH_INDEX], (procToPortDict[pidsplit])[dbconnect_utils.VERSION_INDEX], (procToPortDict[pidsplit])[dbconnect_utils.STATUS_INDEX], (procToPortDict[pidsplit])[dbconnect_utils.COMMANDLINE_INDEX], (procToPortDict[pidsplit])[dbconnect_utils.USER_INDEX]) == 0:
                                    logger.debug('Unable to add ', (procToPortDict[pidsplit])[dbconnect_utils.PROCESSNAME_INDEX])
                                else:
                                    # add key to list of keys to delete later as we've updated them with new entries.
                                    keydeletion.append(pidsplit)
                    else:
                        dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] No TCP port associated with PID [' + pID + ']: ' + lsofLine)
                else:
                    dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Unable to make a process to port map using LSOF: ' + lsofStr)

                # delete keys which are of no value anymore - Daniel La
                for key in keydeletion:
                    logger.debug('key is: ', key)
                    if procToPortDict.has_key(key):
                        logger.debug('deleted key: ', key, ' process: ', (procToPortDict[key])[dbconnect_utils.PROCESSNAME_INDEX])
                        del procToPortDict[key]
            except:
                excInfo = logger.prepareJythonStackTrace('')
                logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Unable to make a process to port map using LSOF: <%s>' % excInfo)
                pass
        else:
            ## Try using netstat and KDB
            try:
                pidToPortMap = {} ## We need a local pid to port map
                netstatLisCmd = 'netstat -Aanf inet | grep "LISTEN"'
                if USE_SUDO == 'true':
                    netstatLisCmd = 'sudo ' + netstatLisCmd
                netstatLisStr = localClient.executeCmd(netstatLisCmd)
                nsLisLines = dbconnect_utils.splitCommandOutput(netstatLisStr.strip())
                if nsLisLines != None:
                    for nsLine in nsLisLines:
                        nsLine = nsLine.strip()
                #        m = re.search('(\w+)\s+tcp\d?\s+\d+\s+\d+\s+(\*|\d+.\d+.\d+.\d+).(\d+)\s+(\*|\d+.\d+.\d+.\d+).(\*|\d+)\s+\S+', nsLine)
                        m = re.search('(\w+)\s+tcp\d?\s+\d+\s+\d+\s+(\*|\d+.\d+.\d+.\d+).(\d+)\s+(\*|\d+.\d+.\d+.\d+).(\*|\d+).*', nsLine)
                        if (m):
                            ipAddress = m.group(2).strip()
                            ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                            ipAddress = dbconnect_utils.fixIP(ipAddress, localClient.getIpAddress())
                            serverPort = m.group(3).strip()
                            pid = getAIXpIDfromAddress(localClient, m.group(1).strip(), USE_SUDO)
                            if pid != None:
                                pidToPortMap[pid] = [ipAddress, serverPort]
                    if pidToPortMap != None and len(pidToPortMap) > 0:
                        for pid in pidToPortMap.keys():
                            if pid in procToPortDict.keys():
                                ipAddress = (pidToPortMap[pid])[0]
                                ## Skip loopback IPs
                                if re.search('127.0.0', ipAddress):
                                    continue
                                serverPort = (pidToPortMap[pid])[1]
                                dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Found port <%s:%s> for pid <%s>' % (ipAddress, serverPort, pid))
                                (procToPortDict[pid])[dbconnect_utils.IP_INDEX] = ipAddress
                                (procToPortDict[pid])[dbconnect_utils.PORT_INDEX] = serverPort
                else:
                    dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Unable to make a process to port map using netstat and kdb: <%s>' % netstatLisStr)
            except:
                excInfo = logger.prepareJythonStackTrace('')
                logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Unable to make a process to port map using netstat and kdb: <%s>' % excInfo)
                pass

        ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Returning process to port dictionary with <%s> items' % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Returning EMPTY process to port dictionary')
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnAIX] Exception: <%s>' % excInfo)
        pass
def getProcToPortDictOnLinux(localClient, USE_SUDO, USE_LSOF):
    try:
        dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnLinux]')
        procToPortDict = {}

        ## Get process OSHs
        ############################################
        try:
            psOut = localClient.executeCmd('ps -e -o pid -o uid -o user -o cputime -o command --cols 4000')
            if psOut == None:
                logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Unable to get list of processes!')
                return None
            psLines = dbconnect_utils.splitCommandOutput(psOut.strip())
            if psLines == None:
                logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Unable to get list of processes!')
                return None
            for psLine in psLines:
                psLine = psLine.strip()
                token = psLine.split(None, 4)
                # Some checks to make sure line is valid
                if(len(token) != 5):
                    continue
                if(not re.search('^\d+$',token[0])):
                    continue
                if(len(token[4]) < 2):
                    continue
                spaceIndex = token[4].find(' ')
                commandPath = ''
                cleanArgs = ''
                if spaceIndex > -1:
                    commandPath = token[4][:spaceIndex]
                    try:
                        cleanArgs = token[4][spaceIndex+1:]
                    except:
                        cleanArgs = ''
                else:
                    commandPath = token[4]
                    cleanArgs = ''
                pid = token[0]
                userName = token[2]
                cleanCommand = ''
                if (commandPath.find('/') == -1) or (commandPath[0] == '['):
                    cleanCommand = commandPath
                else:
                    res2 = re.search('(.*/)([^/]+)',commandPath)
                    if (res2):
                        cleanCommand = res2.group(2)
                    else:
                        continue
                commandLine = cleanCommand + ' ' + cleanArgs
                dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Got PROCESS <%s:%s> with path <%s>, owner <%s>, and command line <%s>' % (pid, cleanCommand, commandPath, userName, commandLine))
                ## {PID:[cleanCommand, listeningPort, ipAddress, path, version, status, processCommandline]}
#                        procToPortDict[pid] = [cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine]
                if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine, userName) == 0:
                    logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s>, owner <%s>, and command line <%s> to the procToPort dictionary' % (pid, cleanCommand, 'Running', commandPath, userName, commandLine))
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Unable to get list of processes: <%s>' % excInfo)
            pass

        ## Use NETSTAT output to create an array of server ports
        ## and map them to server processes
        ############################################
        try:
            netstatLisCmd = 'netstat -anp | grep "LISTEN"'
            if USE_SUDO == 'true':
                netstatLisCmd = 'sudo ' + netstatLisCmd
            netstatLisStr = localClient.executeCmd(netstatLisCmd)
            nsLisLines = dbconnect_utils.splitCommandOutput(netstatLisStr.strip())
            if nsLisLines != None:
                for nsLine in nsLisLines:
                    nsLine = nsLine.strip()
                    dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Got nsLine <%s>' % nsLine)
                    m = re.search('tcp.* (\S+):(\d+).*:.*\s+(\d+|-).*', nsLine)
                    if (m):
                        ipAddress = m.group(1).strip()
                        ## Skip loopback IPs
                        if re.search('127.0.0', ipAddress):
                            continue
                        ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                        ipAddress = dbconnect_utils.fixIP(ipAddress, localClient.getIpAddress())
                        serverPort = m.group(2).strip()
                        pid = m.group(3).strip()
                        dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Got port <%s> for pid <%s>' % (serverPort, pid))
                        if pid != '-' and procToPortDict.has_key(pid):
                            dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Adding port <%s:%s> for process <%s>' % (ipAddress, serverPort, (procToPortDict[pid])[dbconnect_utils.PROCESSNAME_INDEX]))
                            (procToPortDict[pid])[dbconnect_utils.IP_INDEX] = ipAddress
                            (procToPortDict[pid])[dbconnect_utils.PORT_INDEX] = serverPort
                    else:
                        dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Couldn\'t get netstat information (Most likely due to lack of user permissions): ' + nsLine)
            else:
                logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Invalid output from netstat: <%s>' % netstatLisStr)
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Unable to make a process to port map using netstat: <%s>' % excInfo)
            pass

        ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Returning process to port dictionary with <%s> items' % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Returning EMPTY process to port dictionary')
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnLinux] Exception: <%s>' % excInfo)
        pass
def getProcToPortDictOnSolaris(localClient, USE_SUDO, USE_LSOF):
    try:
        dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris]')
        procToPortDict = {}

        ## Get process OSHs
        ############################################
        try:
            psCmd = 'ps -e -o pid -o uid -o user -o time -o args'
            if USE_SUDO == 'true':
                psCmd = 'sudo ' + psCmd
            psOut = localClient.executeCmd(psCmd)
            psLines = dbconnect_utils.splitCommandOutput(psOut.strip())
            if psLines == None:
                logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Unable to get list of processes!')
                return None
            for line in psLines:
                line = line.strip()
                token=line.split(None,4)
                # Some checks to make sure line is valid
                if (len(token) != 5):
                    continue
                if (not re.search('^\d+$',token[0])):
                    continue
                if (len(token[4]) < 2):
                    continue
                spaceIndex = token[4].find(' ')
                commandPath = ''
                cleanArgs = ''
                if spaceIndex > -1:
                    commandPath = token[4][:spaceIndex]
                    try:
                        cleanArgs = token[4][spaceIndex+1:]
                    except:
                        cleanArgs = ''
                else:
                    commandPath = token[4]
                    cleanArgs = ''
                pid = token[0]
                userName = token[2]
                cleanCommand = ''
                cleanPath = ''
                if (commandPath.find('/') == -1) or (commandPath[0] == '['):
                    cleanCommand = commandPath
                    cleanPath = ''
                else:
                    res2 = re.search('(.*/)([^/]+)', commandPath)
                    if (res2):
                        cleanPath = res2.group(1)
                        cleanCommand = res2.group(2)
                    else:
                        continue
                commandLine = cleanCommand + ' ' + cleanArgs
                dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Got PROCESS <%s:%s> with path <%s>, owner <%s>, and command line <%s>' % (pid, cleanCommand, commandPath, userName, commandLine))
                ## {PID:[cleanCommand, listeningPort, ipAddress, path, version, status, processCommandline]}
#                        procToPortDict[pid] = [cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine]
                if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine, userName) == 0:
                    logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s>, owner <%s>, and command line <%s> to the procToPort dictionary' % (pid, cleanCommand, 'Running', commandPath, userName, commandLine))
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Unable to get list of processes: <%s>' % excInfo)
            return None

        ## Use PFILES to map each process to a port and create a dictionary
        ############################################
        try:
            for pID in procToPortDict.keys():
                pFilesCmd = 'pfiles ' + pID + ' 2>/dev/null | grep "sockname: AF_INET"'
                if USE_SUDO == 'true':
                    pFilesCmd = 'sudo ' + pFilesCmd
                pFilesStr = localClient.executeCmd(pFilesCmd)
                if len(pFilesStr) <1:
                    continue
                pFilesLines = dbconnect_utils.splitCommandOutput(pFilesStr.strip())
                if pFilesLines == None:
                    dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Error: Invalid output from pfiles: ' + pFilesStr)
                    continue
                for pFilesLine in pFilesLines:
                    pFilesLine = pFilesLine.strip()
                    m = re.search('.+AF_INET\s+(\d+\.\d+\.\d+\.\d+)\s+port:\s*(\d+)', pFilesLine)
                    if re.search('AFINET6', pFilesLine):
                        m = re.search('.+AF_INET6.*:(\d+\.\d+\.\d+\.\d+)\s+port:\s*(\d+)', pFilesLine)
                    if (m) and m.group(2) != '0':
                        ipAddress = m.group(1).strip()
                        ## Skip loopback IPs
                        if re.search('127.0.0', ipAddress):
                            continue
                        ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                        ipAddress = dbconnect_utils.fixIP(ipAddress, localClient.getIpAddress())
                        serverPort = m.group(2).strip()
                        dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Adding port <%s:%s> for process <%s>' % (ipAddress, serverPort, (procToPortDict[pID])[dbconnect_utils.PROCESSNAME_INDEX]))
                        (procToPortDict[pID])[dbconnect_utils.IP_INDEX] = ipAddress
                        (procToPortDict[pID])[dbconnect_utils.PORT_INDEX] = serverPort
                    else:
                        dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] No TCP port associated with PID [' + pID + ']: ' + pFilesLine)
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Unable to make a process to port map using pfiles: <%s>' % excInfo)
            pass

        ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Returning process to port dictionary with <%s> items' % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Returning EMPTY process to port dictionary')
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Exception: <%s>' % excInfo)
        pass
def getProcToPortDictOnHPUX(localClient, USE_SUDO, USE_LSOF):
    try:
        dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX]')
        procToPortDict = {}

        ## Get process OSHs
        ############################################
        try:
            psOut = localClient.executeCmd('ps -ef')
            psLines = dbconnect_utils.splitCommandOutput(psOut.strip())
            if psLines == None:
                logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Unable to get list of processes!')
                return None
            for psLine in psLines:
                ## Reg for processes with args
                res = re.search('(\w+)\s+?(\d+).*\s\d+\:\d\d\s([0-9a-zA-Z_.\[\]\-+:/]+)\s(.*)', psLine)
                if(res):
                    cleanArgs = res.group(4)
                else:
                    ## Reg for processes with no args
                    res = re.search('(\w+)\s+?(\d+).*\s\d+\:\d\d\s([0-9a-zA-Z_.\-+:/]+)', psLine)
                    if(res):
                        cleanArgs = ''
                if(res):
                    commandPath = res.group(3)
                    pid = res.group(2)
                    userName = res.group(1).strip()
                    cleanCommand = ''
                    if commandPath.find('/') == -1:
                        cleanCommand = commandPath
                    else:
                        res2 = re.search('(.*/)([^/]+)', commandPath)
                        if (res2):
                            cleanCommand = res2.group(2)
                        else:
                            continue
                    commandLine = cleanCommand + ' ' + cleanArgs
                    dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Got PROCESS <%s:%s> with path <%s>, owner <%s>, and command line <%s>' % (pid, cleanCommand, commandPath, userName, commandLine))
                    ## {PID:[cleanCommand, listeningPort, ipAddress, path, version, status, processCommandline]}
#                        procToPortDict[pid] = [cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine]
                    if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine, userName) == 0:
                        logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s>, owner <%s>, and command line <%s> to the procToPort dictionary' % (pid, cleanCommand, 'Running', commandPath, userName, commandLine))
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Unable to get list of processes: <%s>' % excInfo)
            return None

        ## Use LSOF to map each process to a port and create a dictionary
        ############################################
        try:
            pidToPortMap = {} ## We need a local pid to port map
            # lsofCmd = 'lsof -n -P -i | grep -i listen 2>/dev/null'
            lsofCmd = '/usr/local/bin/lsof -n -P -i | grep -i listen 2>/dev/null' # need to specify fullpath - Daniel La
            if USE_SUDO == 'true':
                lsofCmd = 'sudo ' + lsofCmd
            lsofStr = localClient.executeCmd(lsofCmd)
            lsofLines = dbconnect_utils.splitCommandOutput(lsofStr.strip())
            if lsofLines != None:
                for lsofLine in lsofLines:
                    if len(lsofLine) <1:
                        continue
                    lsofLine = lsofLine.strip()
                    m = re.search('\w+\s+(\d+)\s+\w+\s+\w+\s+IPv[4|6].+TCP\s+(\S+):(\d+)\s+\(\w+\)', lsofLine)
                    if (m):
                        pid = m.group(1).strip()
                        ipAddress = m.group(2).strip()
                        ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                        ipAddress = dbconnect_utils.fixIP(ipAddress, localClient.getIpAddress())
                        serverPort = m.group(3).strip()
                        pidToPortMap[pid] = [ipAddress, serverPort]

                if pidToPortMap != None and len(pidToPortMap) > 0:
                    for pid in pidToPortMap.keys():
                        if pid in procToPortDict.keys():
                            ipAddress = (pidToPortMap[pid])[0]
                            ## Skip loopback IPs
                            if re.search('127.0.0', ipAddress):
                                continue
                            serverPort = (pidToPortMap[pid])[1]
                            dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Found port <%s:%s> for pid <%s>' % (ipAddress, serverPort, pid))
                            (procToPortDict[pid])[dbconnect_utils.IP_INDEX] = ipAddress
                            (procToPortDict[pid])[dbconnect_utils.PORT_INDEX] = serverPort
                else:
                    dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] No TCP port associated with PID [' + pID + ']: ' + lsofLine)
            else:
                dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Unable to make a process to port map using LSOF: ' + lsofStr)
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Unable to make a process to port map using LSOF: <%s>' % excInfo)
            pass

        ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Returning process to port dictionary with <%s> items' % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Returning EMPTY process to port dictionary')
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Exception: <%s>' % excInfo)
        pass
コード例 #5
0
def getProcToPortDictOnAIX(localClient, USE_SUDO, USE_LSOF):
    try:
        dbconnect_utils.debugPrint(
            3, '[' + SCRIPT_NAME + ':getProcToPortDictOnAIX]')
        procToPortDict = {}

        ## Get process OSHs
        ############################################
        try:
            psOut = localClient.executeCmd("ps -e -o 'user,pid,time,args'")
            psLines = dbconnect_utils.splitCommandOutput(psOut.strip())
            if psLines == None:
                logger.debug(
                    '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnAIX] Unable to get list of processes!'
                )
                return None
            for psLine in psLines:
                if (re.search('TIME COMMAND', psLine)):
                    continue
                ## Reg for processes with args
                res = re.search(
                    '(\w+)\s+?(\d+).*:\d\d\s([0-9a-zA-Z_.\[\]\-+:/]+)\s(.*)',
                    psLine)
                if (res):
                    cleanArgs = res.group(4)
                else:
                    ## Reg for processes with no args
                    res = re.search(
                        '(\w+)\s+?(\d+).*:\d\d\s([0-9a-zA-Z_.\[\]\-+:/]+)',
                        psLine)
                    if (res):
                        cleanArgs = ''
                if (res):
                    commandPath = res.group(3)
                    pid = res.group(2)
                    userName = res.group(1)
                    cleanCommand = ''
                    if commandPath.find('/') == -1:
                        cleanCommand = commandPath
                    else:
                        res2 = re.search('(.*/)([^/]+)', commandPath)
                        if (res2):
                            cleanCommand = res2.group(2)
                        else:
                            continue
                    commandLine = cleanCommand + ' ' + cleanArgs
                    dbconnect_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnAIX] Got PROCESS <%s:%s> with path <%s>, owner <%s>, and command line <%s>'
                        %
                        (pid, cleanCommand, commandPath, userName, commandLine)
                    )
                    if dbconnect_utils.populateProcToPortDict(
                            procToPortDict, pid, cleanCommand,
                            dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN,
                            commandPath, dbconnect_utils.UNKNOWN, 'Running',
                            commandLine, userName) == 0:
                        logger.debug(
                            '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s>, owner <%s>, and command line <%s> to the procToPort dictionary'
                            % (pid, cleanCommand, 'Running', commandPath,
                               userName, commandLine))
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug(
                '[' + SCRIPT_NAME +
                ':getProcToPortDictOnAIX] Unable to get list of processes: <%s>'
                % excInfo)
            pass

        if USE_LSOF:
            ## Use LSOF to map each process to a port and create a dictionary
            ############################################
            try:
                pidToPortMap = {}  ## We need a local pid to port map
                lsofCmd = 'lsof -n -P -i | grep -i listen 2>/dev/null'
                if USE_SUDO:
                    lsofCmd = 'sudo ' + lsofCmd
                lsofStr = localClient.executeCmd(lsofCmd)
                lsofLines = dbconnect_utils.splitCommandOutput(lsofStr.strip())
                if lsofLines != None:
                    for lsofLine in lsofLines:
                        if len(lsofLine) < 1:
                            continue
                        lsofLine = lsofLine.strip()
                        m = re.search(
                            '\w+\s+(\d+)\s+\w+\s+\w+\s+IPv[4|6].+TCP\s+(\S+):(\d+)\s+\(\w+\)',
                            lsofLine)
                        if (m):
                            pid = m.group(1).strip()
                            ipAddress = m.group(2).strip()
                            ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                            ipAddress = dbconnect_utils.fixIP(
                                ipAddress, localClient.getIpAddress())
                            serverPort = m.group(3).strip()
                            pidToPortMap[pid] = [ipAddress, serverPort]
                    if pidToPortMap != None and len(pidToPortMap) > 0:
                        for pid in pidToPortMap.keys():
                            if pid in procToPortDict.keys():
                                ipAddress = (pidToPortMap[pid])[0]
                                ## Skip loopback IPs
                                if re.search('127.0.0', ipAddress):
                                    continue
                                serverPort = (pidToPortMap[pid])[1]
                                dbconnect_utils.debugPrint(
                                    4, '[' + SCRIPT_NAME +
                                    ':getProcToPortDictOnAIX] Found port <%s:%s> for pid <%s>'
                                    % (ipAddress, serverPort, pid))
                                (procToPortDict[pid]
                                 )[dbconnect_utils.IP_INDEX] = ipAddress
                                (procToPortDict[pid]
                                 )[dbconnect_utils.PORT_INDEX] = serverPort
                    else:
                        dbconnect_utils.debugPrint(
                            3, '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnAIX] No TCP port associated with PID ['
                            + pID + ']: ' + lsofLine)
                else:
                    dbconnect_utils.debugPrint(
                        2, '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnAIX] Unable to make a process to port map using LSOF: '
                        + lsofStr)
            except:
                excInfo = logger.prepareJythonStackTrace('')
                logger.debug(
                    '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnAIX] Unable to make a process to port map using LSOF: <%s>'
                    % excInfo)
                pass
        else:
            ## Try using netstat and KDB
            try:
                pidToPortMap = {}  ## We need a local pid to port map
                netstatLisCmd = 'netstat -Aanf inet | grep "LISTEN"'
                if USE_SUDO:
                    netstatLisCmd = 'sudo ' + netstatLisCmd
                netstatLisStr = localClient.executeCmd(netstatLisCmd)
                nsLisLines = dbconnect_utils.splitCommandOutput(
                    netstatLisStr.strip())
                if nsLisLines != None:
                    for nsLine in nsLisLines:
                        nsLine = nsLine.strip()
                        #		m = re.search('(\w+)\s+tcp\d?\s+\d+\s+\d+\s+(\*|\d+.\d+.\d+.\d+).(\d+)\s+(\*|\d+.\d+.\d+.\d+).(\*|\d+)\s+\S+', nsLine)
                        m = re.search(
                            '(\w+)\s+tcp\d?\s+\d+\s+\d+\s+(\*|\d+.\d+.\d+.\d+).(\d+)\s+(\*|\d+.\d+.\d+.\d+).(\*|\d+).*',
                            nsLine)
                        if (m):
                            ipAddress = m.group(2).strip()
                            ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                            ipAddress = dbconnect_utils.fixIP(
                                ipAddress, localClient.getIpAddress())
                            serverPort = m.group(3).strip()
                            pid = getAIXpIDfromAddress(localClient,
                                                       m.group(1).strip(),
                                                       USE_SUDO)
                            if pid != None:
                                pidToPortMap[pid] = [ipAddress, serverPort]
                    if pidToPortMap != None and len(pidToPortMap) > 0:
                        for pid in pidToPortMap.keys():
                            if pid in procToPortDict.keys():
                                ipAddress = (pidToPortMap[pid])[0]
                                ## Skip loopback IPs
                                if re.search('127.0.0', ipAddress):
                                    continue
                                serverPort = (pidToPortMap[pid])[1]
                                dbconnect_utils.debugPrint(
                                    4, '[' + SCRIPT_NAME +
                                    ':getProcToPortDictOnAIX] Found port <%s:%s> for pid <%s>'
                                    % (ipAddress, serverPort, pid))
                                (procToPortDict[pid]
                                 )[dbconnect_utils.IP_INDEX] = ipAddress
                                (procToPortDict[pid]
                                 )[dbconnect_utils.PORT_INDEX] = serverPort
                else:
                    dbconnect_utils.debugPrint(
                        2, '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnAIX] Unable to make a process to port map using netstat and kdb: <%s>'
                        % netstatLisStr)
            except:
                excInfo = logger.prepareJythonStackTrace('')
                logger.debug(
                    '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnAIX] Unable to make a process to port map using netstat and kdb: <%s>'
                    % excInfo)
                pass

        ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnAIX] Returning process to port dictionary with <%s> items'
                % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnAIX] Returning EMPTY process to port dictionary'
            )
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME +
                     ':getProcToPortDictOnAIX] Exception: <%s>' % excInfo)
        pass
コード例 #6
0
def getProcToPortDictOnWindows(localClient, localFramework):
    try:
        dbconnect_utils.debugPrint(
            3, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows]')
        procToPortDict = {}
        shell = shellutils.ShellUtils(localClient)
        ntcmdErrStr = 'Remote command returned 1(0x1)'
        HOST_IP = localClient.getIpAddress()
        HOSTID = localFramework.getDestinationAttribute('hostId')

        ## Get process OSHs using NTCMD HR script
        ############################################
        try:
            processOSHV = ObjectStateHolderVector()
            if (NTCMD_HR_Dis_Process_Lib.discoverProcessesByWmic(
                    shell, processOSHV, HOSTID, localFramework)) == 1 or (
                        NTCMD_HR_Dis_Process_Lib.discoverProcesses(
                            shell, processOSHV, HOSTID, localFramework)) == 1:
                ## We have an OSHV, extract OSHs from it
                oshvIndex = 0
                try:
                    while processOSHV.get(oshvIndex):
                        someOSH = processOSHV.get(oshvIndex)
                        if someOSH.getObjectClass() == 'process':
                            processDict = dbconnect_utils.getAttributeValuesFromOSH(
                                someOSH, [
                                    'process_pid', 'data_name',
                                    'process_cmdline', 'process_path'
                                ])
                            ## Name
                            processName = processDict['data_name']
                            if processName == None or processName == '' or len(
                                    processName) < 1:
                                ## We don't care about nameless processes
                                continue
                            pid = processDict['process_pid']  ## PID
                            processPath = processDict['process_path']  ## Path
                            processPath = string.replace(processPath, '"', '')
                            processCmdline = processDict[
                                'process_cmdline']  ## Command line
                            processCmdline = string.replace(
                                processCmdline, '"', '')
                            ## Add this to the dictionary
                            dbconnect_utils.debugPrint(
                                4, '[' + SCRIPT_NAME +
                                ':getProcToPortDictOnWindows] Got PROCESS <%s:%s> with path <%s> and command line <%s>'
                                %
                                (pid, processName, processPath, processCmdline)
                            )
                        ## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]}
#						procToPortDict[pid] = [processName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, processPath, dbconnect_utils.UNKNOWN, 'Running', processCmdline]
                        if dbconnect_utils.populateProcToPortDict(
                                procToPortDict, pid, processName,
                                dbconnect_utils.UNKNOWN,
                                dbconnect_utils.UNKNOWN, processPath,
                                dbconnect_utils.UNKNOWN, 'Running',
                                processCmdline) == 0:
                            logger.debug(
                                '[' + SCRIPT_NAME +
                                ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s> and command line <%s> to the procToPort dictionary'
                                % (pid, processName, 'Running', processPath,
                                   processCmdline))
                        oshvIndex = oshvIndex + 1
                except ArrayIndexOutOfBoundsException:
                    dbconnect_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnWindows] Array OOB exception while getting process CIs from OSHV. Ignoring because this is expected...'
                    )
                    pass
            else:
                ## We don't have an OSHV
                dbconnect_utils.debugPrint(
                    3, '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnWindows] Unable to get list of processes'
                )
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug(
                '[' + SCRIPT_NAME +
                ':getProcToPortDictOnWindows] Unable to get list of processes: <%s>'
                % excInfo)
            pass

        ## Add windows services to the list of processes
        ############################################
        ## First try WMIC because we can get a PID
        ## If that doesn't work, fallback on the OOTB NTCMD HR script
        try:
            buffer = shell.execCmd(
                'wmic service get displayname, pathname, processid, started /format:csv < %SystemRoot%\win.ini'
            )
            dbconnect_utils.debugPrint(
                4, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnWindows] Output for wmic process command: %s'
                % buffer)
            reg_mamRc = shell.getLastCmdReturnCode()
            if (reg_mamRc == 0):
                ## WMIC worked!!
                wmicLines = buffer.split('\n')
                fakePid = 0
                # Each line: HOSTNAME,SERVICENAME,EXE-PATH,PID
                for wmicLine in wmicLines:
                    tokens = wmicLine.split(',')
                    numTokens = len(tokens)
                    if (tokens == None) or (numTokens < 1):
                        continue
                    if tokens[0].strip() == 'Node':
                        continue
                    if (numTokens < 4):
                        continue
                    serviceName = tokens[numTokens - 4].strip()
                    serviceStatus = dbconnect_utils.UNKNOWN
                    if tokens[numTokens - 1].strip().lower() == 'true':
                        serviceStatus = 'Running'
                    else:
                        serviceStatus = 'Not Running'
                    pid = tokens[numTokens - 2].strip()
                    ## Don't bother with SYSTEM services that have a pid of -1
                    if (pid != '-1' and pid.isnumeric()):
                        # Get the command line
                        serviceCmdline = tokens[numTokens - 3].strip()
                        serviceCmdline = serviceCmdline.strip()[0:2499]
                        serviceCmdline = string.replace(
                            serviceCmdline, '"', '')
                        # Set process path to command line
                        servicePath = serviceCmdline
                        ## While using services, we sometimes need a fake PID because
                        ## the service may not be running and the corresponding PID will be 0
                        if pid == '0':
                            pid = 'SERVICE ' + str(fakePid)
                            fakePid = fakePid + 1
                            dbconnect_utils.debugPrint(
                                4, '[' + SCRIPT_NAME +
                                ':getProcToPortDictOnWindows] Using fake PID <%s> for service <%s>'
                                % (pid, serviceName))
                        ## Got everything, make the array
                        dbconnect_utils.debugPrint(
                            4, '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnWindows] Got SERVICE <%s (%s)> with PID <%s>, command line <%s>, command path <%s>'
                            % (serviceName, serviceStatus, pid, serviceCmdline,
                               servicePath))
                        ## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]}
                        #						procToPortDict[pid] = [serviceName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, servicePath, dbconnect_utils.UNKNOWN, serviceStatus, serviceCmdline]
                        if dbconnect_utils.populateProcToPortDict(
                                procToPortDict, pid, serviceName,
                                dbconnect_utils.UNKNOWN, HOST_IP, servicePath,
                                dbconnect_utils.UNKNOWN, serviceStatus,
                                serviceCmdline) == 0:
                            logger.debug(
                                '[' + SCRIPT_NAME +
                                ':getProcToPortDictOnWindows] Unable to add SERVICE <%s:%s> (%s) with path <%s> and command line <%s> to the procToPort dictionary'
                                % (pid, serviceName, serviceStatus,
                                   servicePath, serviceCmdline))
            else:
                ## WMIC didn't work. Get service OSHs using NTCMD HR script
                dbconnect_utils.debugPrint(
                    3, '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnWindows] WMIC didn\'t work, trying NTCMD HR script'
                )
                servicesOSHV = NTCMD_HR_REG_Service_Lib.doService(
                    shell, modeling.createHostOSH(HOST_IP))
                ## Extract OSHs from vector
                oshvIndex = 0
                try:
                    while servicesOSHV.get(oshvIndex):
                        someOSH = servicesOSHV.get(oshvIndex)
                        if someOSH.getObjectClass() == 'service':
                            serviceDict = dbconnect_utils.getAttributeValuesFromOSH(
                                someOSH, [
                                    'data_name', 'service_pathtoexec',
                                    'service_commandline',
                                    'service_operatingstatus'
                                ])
                            ## Name
                            serviceName = serviceDict['data_name']
                            if serviceName == None or serviceName == '' or len(
                                    serviceName) < 1:
                                ## We don't care about nameless services
                                continue
                            pid = 'SERVICE ' + str(oshvIndex)  ## PID (fake)
                            servicePath = serviceDict[
                                'service_pathtoexec']  ## Install path
                            servicePath = string.replace(servicePath, '"', '')
                            serviceCmdline = serviceDict[
                                'service_commandline']  ## Command line
                            serviceCmdline = string.replace(
                                serviceCmdline, '"', '')
                            serviceStatus = serviceDict[
                                'service_operatingstatus']  ## Status
                            ## Add this to the dictionary
                            dbconnect_utils.debugPrint(
                                4, '[' + SCRIPT_NAME +
                                ':getProcToPortDictOnWindows] Got <%s:%s> with installPath <%s> and commandline <%s>'
                                %
                                (pid, serviceName, servicePath, serviceCmdline)
                            )
                        ## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]}
#						procToPortDict[pid] = [serviceName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, servicePath, dbconnect_utils.UNKNOWN, serviceStatus, serviceCmdline]
                        if dbconnect_utils.populateProcToPortDict(
                                procToPortDict, pid, serviceName,
                                dbconnect_utils.UNKNOWN, HOST_IP, servicePath,
                                dbconnect_utils.UNKNOWN, serviceStatus,
                                serviceCmdline) == 0:
                            logger.debug(
                                '[' + SCRIPT_NAME +
                                ':getProcToPortDictOnWindows] Unable to add SERVICE <%s:%s> (%s) with path <%s> and command line <%s> to the procToPort dictionary'
                                % (pid, serviceName, serviceStatus,
                                   servicePath, serviceCmdline))
                        oshvIndex = oshvIndex + 1
                except ArrayIndexOutOfBoundsException:
                    dbconnect_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnWindows] Array OOB exception while getting service CIs from OSHV. Ignoring because this is expected...'
                    )
                    pass
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug(
                '[' + SCRIPT_NAME +
                ':getProcToPortDictOnWindows] Unable to get list of services: <%s>'
                % excInfo)
            pass

        ## Add installed software to the list of processes
        ############################################
        try:
            ## Get installed software OSHs using NTCMD HR script
            softwareOSHV = ObjectStateHolderVector()
            gotSoftwareOshs = NTCMD_HR_REG_Software_Lib.doSoftware(
                shell, modeling.createHostOSH(HOST_IP), softwareOSHV)
            ## Extract OSHs from vector
            oshvIndex = 0
            while gotSoftwareOshs and softwareOSHV.get(oshvIndex):
                someOSH = softwareOSHV.get(oshvIndex)
                if someOSH.getObjectClass() == 'software':
                    softwareDict = dbconnect_utils.getAttributeValuesFromOSH(
                        someOSH, [
                            'data_name', 'software_installpath',
                            'software_version'
                        ])
                    ## Name
                    softwareName = softwareDict['data_name']
                    if not softwareName:
                        ## We don't care about nameless software
                        continue
                    pid = 'SOFTWARE ' + str(oshvIndex)  ## PID (fake)
                    softwareInstallPath = softwareDict[
                        'software_installpath']  ## Install path
                    softwareVersion = softwareDict[
                        'software_version']  ## Version
                    ## Add this to the dictionary
                    dbconnect_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnWindows] Got <%s:%s> with installPath <%s> and version <%s>'
                        % (pid, softwareName, softwareInstallPath,
                           softwareVersion))
                    ## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]}
                    #					procToPortDict[pid] = [softwareName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, softwareInstallPath, softwareVersion, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN]
                    if dbconnect_utils.populateProcToPortDict(
                            procToPortDict, pid, softwareName,
                            dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN,
                            softwareInstallPath, softwareVersion,
                            dbconnect_utils.UNKNOWN,
                            dbconnect_utils.UNKNOWN) == 0:
                        logger.debug(
                            '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnWindows] Unable to add SOFTWARE <%s:%s> (%s) with path <%s> and command line <%s> to the procToPort dictionary'
                            % (pid, softwareName, dbconnect_utils.UNKNOWN,
                               softwareInstallPath, dbconnect_utils.UNKNOWN))
                oshvIndex = oshvIndex + 1
        except ArrayIndexOutOfBoundsException:
            dbconnect_utils.debugPrint(
                4, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnWindows] Array OOB exception while getting software CIs from OSHV. Ignoring because this is expected...'
            )
            pass
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug(
                '[' + SCRIPT_NAME +
                ':getProcToPortDictOnWindows] Unable to get list of software: <%s>'
                % excInfo)
            pass

        ## Use NETSTAT output to create an array of server ports
        ## and map them to server processes
        ############################################
        try:
            netstatLisStr = shell.execCmd(
                'netstat -aon -p tcp | find "LISTENING"')
            nsStrOk = 'false'
            nsLisLines = None
            if netstatLisStr.find(ntcmdErrStr) != -1 or len(netstatLisStr) < 1:
                nsStrOk = 'false'
            elif re.search('\r\n', netstatLisStr):
                nsLisLines = netstatLisStr.split('\r\n')
                nsStrOk = 'true'
            elif re.search('\n', netstatLisStr):
                nsLisLines = netstatLisStr.split('\n')
                nsStrOk = 'true'
            if nsStrOk == 'true':
                for line in nsLisLines:
                    line = line.strip()
                    m = re.search(
                        '\S+\s+(\d+.\d+.\d+.\d+):(\d+)\s+\d+.\d+.\d+.\d+:\d+\s+\S+\s+(\d+).*',
                        line)
                    if (m):
                        ipAddress = m.group(1).strip()
                        ## Skip loopback IPs
                        if re.search('127.0.0', ipAddress):
                            continue
                        ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                        ipAddress = dbconnect_utils.fixIP(
                            ipAddress, localClient.getIpAddress())
                        serverPort = m.group(2).strip()
                        pid = m.group(3)
                        dbconnect_utils.debugPrint(
                            4, '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnWindows] Got port <%s> for pid <%s>'
                            % (serverPort, pid))
                        if pid != '-' and procToPortDict.has_key(pid):
                            dbconnect_utils.debugPrint(
                                4, '[' + SCRIPT_NAME +
                                ':getProcToPortDictOnWindows] Adding port <%s:%s> for process <%s>'
                                % (ipAddress, serverPort,
                                   (procToPortDict[pid])[0]))
                            (procToPortDict[pid]
                             )[dbconnect_utils.IP_INDEX] = ipAddress
                            (procToPortDict[pid]
                             )[dbconnect_utils.PORT_INDEX] = serverPort
                        dbconnect_utils.debugPrint(
                            4, '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnWindows] Got port <%s> for pid <%s>'
                            % (serverPort, pid))
                    else:
                        dbconnect_utils.debugPrint(
                            3, '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnWindows] Couldn\'t get process information (Most likely due to lack of user permissions): '
                            + line)
            else:
                dbconnect_utils.debugPrint(
                    2, '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnWindows] Invalid output from netstat: <%s>'
                    % netstatLisStr)
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug(
                '[' + SCRIPT_NAME +
                ':getProcToPortDictOnWindows] Unable to make a process to port map using netstat: <%s>'
                % excInfo)
            pass

        ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnWindows] Returning process to port dictionary with <%s> items'
                % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnWindows] Returning EMPTY process to port dictionary'
            )
            return None
    except:
        excInfo = logger.prepareJythonStackTrace('')
        dbconnect_utils.debugPrint(
            '[' + SCRIPT_NAME +
            ':getProcToPortDictOnWindows] Exception: <%s>' % excInfo)
        pass
コード例 #7
0
def getProcToPortDictOnSolaris(localClient, USE_SUDO, USE_LSOF):
    try:
        dbconnect_utils.debugPrint(
            3, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris]')
        procToPortDict = {}

        ## Get process OSHs
        ############################################
        try:
            psCmd = 'ps -e -o pid -o uid -o user -o time -o args'
            if USE_SUDO:
                psCmd = 'sudo ' + psCmd
            psOut = localClient.executeCmd(psCmd)
            psLines = dbconnect_utils.splitCommandOutput(psOut.strip())
            if psLines == None:
                logger.debug(
                    '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnSolaris] Unable to get list of processes!'
                )
                return None
            for line in psLines:
                line = line.strip()
                token = line.split(None, 4)
                # Some checks to make sure line is valid
                if (len(token) != 5):
                    continue
                if (not re.search('^\d+$', token[0])):
                    continue
                if (len(token[4]) < 2):
                    continue
                spaceIndex = token[4].find(' ')
                commandPath = ''
                cleanArgs = ''
                if spaceIndex > -1:
                    commandPath = token[4][:spaceIndex]
                    try:
                        cleanArgs = token[4][spaceIndex + 1:]
                    except:
                        cleanArgs = ''
                else:
                    commandPath = token[4]
                    cleanArgs = ''
                pid = token[0]
                userName = token[2]
                cleanCommand = ''
                cleanPath = ''
                if (commandPath.find('/') == -1) or (commandPath[0] == '['):
                    cleanCommand = commandPath
                    cleanPath = ''
                else:
                    res2 = re.search('(.*/)([^/]+)', commandPath)
                    if (res2):
                        cleanPath = res2.group(1)
                        cleanCommand = res2.group(2)
                    else:
                        continue
                commandLine = cleanCommand + ' ' + cleanArgs
                dbconnect_utils.debugPrint(
                    4, '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnSolaris] Got PROCESS <%s:%s> with path <%s>, owner <%s>, and command line <%s>'
                    % (pid, cleanCommand, commandPath, userName, commandLine))
                ## {PID:[cleanCommand, listeningPort, ipAddress, path, version, status, processCommandline]}
                #						procToPortDict[pid] = [cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine]
                if dbconnect_utils.populateProcToPortDict(
                        procToPortDict, pid, cleanCommand,
                        dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN,
                        commandPath, dbconnect_utils.UNKNOWN, 'Running',
                        commandLine, userName) == 0:
                    logger.debug(
                        '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s>, owner <%s>, and command line <%s> to the procToPort dictionary'
                        % (pid, cleanCommand, 'Running', commandPath, userName,
                           commandLine))
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug(
                '[' + SCRIPT_NAME +
                ':getProcToPortDictOnSolaris] Unable to get list of processes: <%s>'
                % excInfo)
            return None
        allowPFiles = getGlobalSetting().getPropertyBooleanValue(
            'allowPFilesOnSunOS', False)
        if USE_LSOF:
            handleProcessToPortByLsof(USE_SUDO, localClient, procToPortDict)
        elif allowPFiles:
            handleProcessToPortByPFile(
                USE_SUDO, localClient,
                procToPortDict)  ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnSolaris] Returning process to port dictionary with <%s> items'
                % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnSolaris] Returning EMPTY process to port dictionary'
            )
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME +
                     ':getProcToPortDictOnSolaris] Exception: <%s>' % excInfo)
        pass
コード例 #8
0
def getProcToPortDictOnHPUX(localClient, USE_SUDO, USE_LSOF):
    try:
        dbconnect_utils.debugPrint(
            3, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX]')
        procToPortDict = {}

        ## Get process OSHs
        ############################################
        try:
            psOut = localClient.executeCmd('ps -ef')
            psLines = dbconnect_utils.splitCommandOutput(psOut.strip())
            if psLines == None:
                logger.debug(
                    '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnHPUX] Unable to get list of processes!'
                )
                return None
            for psLine in psLines:
                ## Reg for processes with args
                res = re.search(
                    '(\w+)\s+?(\d+).*\s\d+\:\d\d\s([0-9a-zA-Z_.\[\]\-+:/]+)\s(.*)',
                    psLine)
                if (res):
                    cleanArgs = res.group(4)
                else:
                    ## Reg for processes with no args
                    res = re.search(
                        '(\w+)\s+?(\d+).*\s\d+\:\d\d\s([0-9a-zA-Z_.\-+:/]+)',
                        psLine)
                    if (res):
                        cleanArgs = ''
                if (res):
                    commandPath = res.group(3)
                    pid = res.group(2)
                    userName = res.group(1).strip()
                    cleanCommand = ''
                    if commandPath.find('/') == -1:
                        cleanCommand = commandPath
                    else:
                        res2 = re.search('(.*/)([^/]+)', commandPath)
                        if (res2):
                            cleanCommand = res2.group(2)
                        else:
                            continue
                    commandLine = cleanCommand + ' ' + cleanArgs
                    dbconnect_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnHPUX] Got PROCESS <%s:%s> with path <%s>, owner <%s>, and command line <%s>'
                        %
                        (pid, cleanCommand, commandPath, userName, commandLine)
                    )
                    ## {PID:[cleanCommand, listeningPort, ipAddress, path, version, status, processCommandline]}
                    #						procToPortDict[pid] = [cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine]
                    if dbconnect_utils.populateProcToPortDict(
                            procToPortDict, pid, cleanCommand,
                            dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN,
                            commandPath, dbconnect_utils.UNKNOWN, 'Running',
                            commandLine, userName) == 0:
                        logger.debug(
                            '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s>, owner <%s>, and command line <%s> to the procToPort dictionary'
                            % (pid, cleanCommand, 'Running', commandPath,
                               userName, commandLine))
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug(
                '[' + SCRIPT_NAME +
                ':getProcToPortDictOnHPUX] Unable to get list of processes: <%s>'
                % excInfo)
            return None

        ## Use LSOF to map each process to a port and create a dictionary
        ############################################
        handleProcessToPortByLsof(USE_SUDO, localClient, procToPortDict)
        ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnHPUX] Returning process to port dictionary with <%s> items'
                % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnHPUX] Returning EMPTY process to port dictionary'
            )
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME +
                     ':getProcToPortDictOnHPUX] Exception: <%s>' % excInfo)
        pass
コード例 #9
0
def getProcToPortDictOnLinux(localClient, USE_SUDO, USE_LSOF):
    try:
        dbconnect_utils.debugPrint(
            3, '[' + SCRIPT_NAME + ':getProcToPortDictOnLinux]')
        procToPortDict = {}

        ## Get process OSHs
        ############################################
        try:
            psOut = localClient.executeCmd(
                'ps -e -o pid -o uid -o user -o cputime -o command --cols 4000'
            )
            if psOut == None:
                logger.debug(
                    '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnLinux] Unable to get list of processes!'
                )
                return None
            psLines = dbconnect_utils.splitCommandOutput(psOut.strip())
            if psLines == None:
                logger.debug(
                    '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnLinux] Unable to get list of processes!'
                )
                return None
            for psLine in psLines:
                psLine = psLine.strip()
                token = psLine.split(None, 4)
                # Some checks to make sure line is valid
                if (len(token) != 5):
                    continue
                if (not re.search('^\d+$', token[0])):
                    continue
                if (len(token[4]) < 2):
                    continue
                spaceIndex = token[4].find(' ')
                commandPath = ''
                cleanArgs = ''
                if spaceIndex > -1:
                    commandPath = token[4][:spaceIndex]
                    try:
                        cleanArgs = token[4][spaceIndex + 1:]
                    except:
                        cleanArgs = ''
                else:
                    commandPath = token[4]
                    cleanArgs = ''
                pid = token[0]
                userName = token[2]
                cleanCommand = ''
                if (commandPath.find('/') == -1) or (commandPath[0] == '['):
                    cleanCommand = commandPath
                else:
                    res2 = re.search('(.*/)([^/]+)', commandPath)
                    if (res2):
                        cleanCommand = res2.group(2)
                    else:
                        continue
                commandLine = cleanCommand + ' ' + cleanArgs
                dbconnect_utils.debugPrint(
                    4, '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnLinux] Got PROCESS <%s:%s> with path <%s>, owner <%s>, and command line <%s>'
                    % (pid, cleanCommand, commandPath, userName, commandLine))
                ## {PID:[cleanCommand, listeningPort, ipAddress, path, version, status, processCommandline]}
                #						procToPortDict[pid] = [cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine]
                if dbconnect_utils.populateProcToPortDict(
                        procToPortDict, pid, cleanCommand,
                        dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN,
                        commandPath, dbconnect_utils.UNKNOWN, 'Running',
                        commandLine, userName) == 0:
                    logger.debug(
                        '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s>, owner <%s>, and command line <%s> to the procToPort dictionary'
                        % (pid, cleanCommand, 'Running', commandPath, userName,
                           commandLine))
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug(
                '[' + SCRIPT_NAME +
                ':getProcToPortDictOnLinux] Unable to get list of processes: <%s>'
                % excInfo)
            pass

        ## Use NETSTAT output to create an array of server ports
        ## and map them to server processes
        ############################################
        try:
            netstatLisCmd = 'netstat -anp | grep "LISTEN"'
            if USE_SUDO:
                netstatLisCmd = 'sudo ' + netstatLisCmd
            netstatLisStr = localClient.executeCmd(netstatLisCmd)
            nsLisLines = dbconnect_utils.splitCommandOutput(
                netstatLisStr.strip())
            if nsLisLines != None:
                for nsLine in nsLisLines:
                    nsLine = nsLine.strip()
                    dbconnect_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getProcToPortDictOnLinux] Got nsLine <%s>' % nsLine)
                    m = re.search('tcp.* (\S+):(\d+).*:.*\s+(\d+|-).*', nsLine)
                    if (m):
                        ipAddress = m.group(1).strip()
                        ## Skip loopback IPs
                        if re.search('127.0.0', ipAddress):
                            continue
                        ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                        ipAddress = dbconnect_utils.fixIP(
                            ipAddress, localClient.getIpAddress())
                        serverPort = m.group(2).strip()
                        pid = m.group(3).strip()
                        dbconnect_utils.debugPrint(
                            4, '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnLinux] Got port <%s> for pid <%s>'
                            % (serverPort, pid))
                        if pid != '-' and procToPortDict.has_key(pid):
                            dbconnect_utils.debugPrint(
                                4, '[' + SCRIPT_NAME +
                                ':getProcToPortDictOnLinux] Adding port <%s:%s> for process <%s>'
                                % (ipAddress, serverPort,
                                   (procToPortDict[pid]
                                    )[dbconnect_utils.PROCESSNAME_INDEX]))
                            (procToPortDict[pid]
                             )[dbconnect_utils.IP_INDEX] = ipAddress
                            (procToPortDict[pid]
                             )[dbconnect_utils.PORT_INDEX] = serverPort
                    else:
                        dbconnect_utils.debugPrint(
                            2, '[' + SCRIPT_NAME +
                            ':getProcToPortDictOnLinux] Couldn\'t get netstat information (Most likely due to lack of user permissions): '
                            + nsLine)
            else:
                logger.debug(
                    '[' + SCRIPT_NAME +
                    ':getProcToPortDictOnLinux] Invalid output from netstat: <%s>'
                    % netstatLisStr)
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug(
                '[' + SCRIPT_NAME +
                ':getProcToPortDictOnLinux] Unable to make a process to port map using netstat: <%s>'
                % excInfo)
            pass

        ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnLinux] Returning process to port dictionary with <%s> items'
                % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getProcToPortDictOnLinux] Returning EMPTY process to port dictionary'
            )
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME +
                     ':getProcToPortDictOnLinux] Exception: <%s>' % excInfo)
        pass
def getProcToPortDictOnWindows(localClient, localFramework):
    try:
        dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows]')
        procToPortDict = {}
        shell = shellutils.ShellUtils(localClient)
        ntcmdErrStr = 'Remote command returned 1(0x1)'
        HOST_IP = localClient.getIpAddress()
        HOSTID = localFramework.getDestinationAttribute('hostId')

        ## Get process OSHs using NTCMD HR script
        ############################################
        try:
            processOSHV = ObjectStateHolderVector()
            if (NTCMD_HR_Dis_Process_Lib.discoverProcessesByWmic(shell, processOSHV, HOSTID, localFramework)) == 1 or (NTCMD_HR_Dis_Process_Lib.discoverProcesses(shell, processOSHV, HOSTID, localFramework)) == 1:
                ## We have an OSHV, extract OSHs from it
                oshvIndex = 0
                try:
                    while processOSHV.get(oshvIndex):
                        someOSH = processOSHV.get(oshvIndex)
                        if someOSH.getObjectClass() == 'process':
                            processDict = dbconnect_utils.getAttributeValuesFromOSH(someOSH, ['process_pid', 'data_name', 'process_cmdline', 'process_path'])
                            ## Name
                            processName = processDict['data_name']
                            if processName == None or processName == '' or len(processName) <1:
                                ## We don't care about nameless processes
                                continue
                            pid = processDict['process_pid']                ## PID
                            processPath = processDict['process_path']        ## Path
                            processPath = string.replace(processPath, '"', '')
                            processCmdline = processDict['process_cmdline']    ## Command line
                            processCmdline = string.replace(processCmdline, '"', '')
                            ## Add this to the dictionary
                            dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Got PROCESS <%s:%s> with path <%s> and command line <%s>' % (pid, processName, processPath, processCmdline))
                        ## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]}
#                        procToPortDict[pid] = [processName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, processPath, dbconnect_utils.UNKNOWN, 'Running', processCmdline]
                        if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, processName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, processPath, dbconnect_utils.UNKNOWN, 'Running', processCmdline) == 0:
                            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s> and command line <%s> to the procToPort dictionary' % (pid, processName, 'Running', processPath, processCmdline))
                        oshvIndex = oshvIndex + 1
                except ArrayIndexOutOfBoundsException:
                    dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Array OOB exception while getting process CIs from OSHV. Ignoring because this is expected...')
                    pass
            else:
                ## We don't have an OSHV
                dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to get list of processes')
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to get list of processes: <%s>' % excInfo)
            pass

        ## Add windows services to the list of processes
        ############################################
        ## First try WMIC because we can get a PID
        ## If that doesn't work, fallback on the OOTB NTCMD HR script
        try:
            buffer = shell.execCmd('wmic service get displayname, pathname, processid, started /format:csv < %SystemRoot%\win.ini')
            dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Output for wmic process command: %s' % buffer)
            reg_mamRc =    shell.getLastCmdReturnCode()
            if (reg_mamRc == 0):
                ## WMIC worked!!
                wmicLines = buffer.split('\n')
                fakePid = 0
                # Each line: HOSTNAME,SERVICENAME,EXE-PATH,PID
                for wmicLine in    wmicLines:
                    tokens = wmicLine.split(',')
                    numTokens = len(tokens)
                    if (tokens == None) or (numTokens < 1) :
                        continue
                    if tokens[0].strip() == 'Node':
                        continue
                    if (numTokens < 4):
                        continue
                    serviceName = tokens[numTokens - 4].strip()
                    serviceStatus = dbconnect_utils.UNKNOWN
                    if tokens[numTokens - 1].strip().lower() == 'true':
                        serviceStatus = 'Running'
                    else:
                        serviceStatus = 'Not Running'
                    pid = tokens[numTokens - 2].strip()
                    ## Don't bother with SYSTEM services that have a pid of -1
                    if(pid != '-1' and pid.isnumeric()):
                        # Get the command line
                        serviceCmdline = tokens[numTokens - 3].strip()
                        serviceCmdline = serviceCmdline.strip()[0:2499]
                        serviceCmdline = string.replace(serviceCmdline, '"', '')
                        # Set process path to command line
                        servicePath = serviceCmdline
                        ## While using services, we sometimes need a fake PID because
                        ## the service may not be running and the corresponding PID will be 0
                        if pid == '0':
                            pid = 'SERVICE ' + str(fakePid)
                            fakePid = fakePid + 1
                            dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Using fake PID <%s> for service <%s>' % (pid, serviceName))
                        ## Got everything, make the array
                        dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Got SERVICE <%s (%s)> with PID <%s>, command line <%s>, command path <%s>' % (serviceName, serviceStatus, pid, serviceCmdline, servicePath))
                        ## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]}
#                        procToPortDict[pid] = [serviceName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, servicePath, dbconnect_utils.UNKNOWN, serviceStatus, serviceCmdline]
                        if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, serviceName, dbconnect_utils.UNKNOWN, HOST_IP, servicePath, dbconnect_utils.UNKNOWN, serviceStatus, serviceCmdline) == 0:
                            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add SERVICE <%s:%s> (%s) with path <%s> and command line <%s> to the procToPort dictionary' % (pid, serviceName, serviceStatus, servicePath, serviceCmdline))
            else:
                ## WMIC didn't work. Get service OSHs using NTCMD HR script
                dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] WMIC didn\'t work, trying NTCMD HR script')
                servicesOSHV = NTCMD_HR_REG_Service_Lib.doService(shell, modeling.createHostOSH(HOST_IP))
                ## Extract OSHs from vector
                oshvIndex = 0
                try:
                    while servicesOSHV.get(oshvIndex):
                        someOSH = servicesOSHV.get(oshvIndex)
                        if someOSH.getObjectClass() == 'service':
                            serviceDict = dbconnect_utils.getAttributeValuesFromOSH(someOSH, ['data_name', 'service_pathtoexec', 'service_commandline', 'service_operatingstatus'])
                            ## Name
                            serviceName = serviceDict['data_name']
                            if serviceName == None or serviceName == '' or len(serviceName) <1:
                                ## We don't care about nameless services
                                continue
                            pid = 'SERVICE ' + str(oshvIndex)                        ## PID (fake)
                            servicePath = serviceDict['service_pathtoexec']        ## Install path
                            servicePath = string.replace(servicePath, '"', '')
                            serviceCmdline = serviceDict['service_commandline']        ## Command line
                            serviceCmdline = string.replace(serviceCmdline, '"', '')
                            serviceStatus = serviceDict['service_operatingstatus']        ## Status
                            if serviceStatus == 'true':
                                serviceStatus = 'Running'
                            else:
                                serviceStatus = 'Not Running'
                            ## Add this to the dictionary
                            dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Got <%s:%s> with installPath <%s> and commandline <%s>' % (pid, serviceName, servicePath, serviceCmdline))
                        ## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]}
#                        procToPortDict[pid] = [serviceName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, servicePath, dbconnect_utils.UNKNOWN, serviceStatus, serviceCmdline]
                        if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, serviceName, dbconnect_utils.UNKNOWN, HOST_IP, servicePath, dbconnect_utils.UNKNOWN, serviceStatus, serviceCmdline) == 0:
                            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add SERVICE <%s:%s> (%s) with path <%s> and command line <%s> to the procToPort dictionary' % (pid, serviceName, serviceStatus, servicePath, serviceCmdline))
                        oshvIndex = oshvIndex + 1
                except ArrayIndexOutOfBoundsException:
                    dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Array OOB exception while getting service CIs from OSHV. Ignoring because this is expected...')
                    pass
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to get list of services: <%s>' % excInfo)
            pass

        ## Add installed software to the list of processes
        ############################################
        try:
            ## Get installed software OSHs using NTCMD HR script
            softwareOSHV = ObjectStateHolderVector()
            gotSoftwareOshs = NTCMD_HR_REG_Software_Lib.doSoftware(shell, modeling.createHostOSH(HOST_IP), softwareOSHV)
            ## Extract OSHs from vector
            oshvIndex = 0
            while gotSoftwareOshs and softwareOSHV.get(oshvIndex):
                someOSH = softwareOSHV.get(oshvIndex)
                if someOSH.getObjectClass() == 'software':
                    softwareDict = dbconnect_utils.getAttributeValuesFromOSH(someOSH, ['data_name', 'software_installpath', 'software_version'])
                    ## Name
                    softwareName = softwareDict['data_name']
                    if not softwareName:
                        ## We don't care about nameless software
                        continue
                    pid = 'SOFTWARE ' + str(oshvIndex)                        ## PID (fake)
                    softwareInstallPath = softwareDict['software_installpath']        ## Install path
                    softwareVersion = softwareDict['software_version']            ## Version
                    ## Add this to the dictionary
                    dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Got <%s:%s> with installPath <%s> and version <%s>' % (pid, softwareName, softwareInstallPath, softwareVersion))
                    ## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]}
#                    procToPortDict[pid] = [softwareName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, softwareInstallPath, softwareVersion, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN]
                    if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, softwareName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, softwareInstallPath, softwareVersion, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN) == 0:
                        logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add SOFTWARE <%s:%s> (%s) with path <%s> and command line <%s> to the procToPort dictionary' % (pid, softwareName, dbconnect_utils.UNKNOWN, softwareInstallPath, dbconnect_utils.UNKNOWN))
                oshvIndex = oshvIndex + 1
        except ArrayIndexOutOfBoundsException:
            dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Array OOB exception while getting software CIs from OSHV. Ignoring because this is expected...')
            pass
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to get list of software: <%s>' % excInfo)
            pass

        ## Use NETSTAT output to create an array of server ports
        ## and map them to server processes
        ############################################
        ## Updated by Daniel La: updated to handle situation where a process can listen on multiple ports.
        try:
            keydeletion = [] # keys to delete - Daniel La
            netstatLisStr = shell.execCmd('netstat -aon -p tcp | find "LISTENING"')
            nsStrOk = 'false'
            nsLisLines = None
            if netstatLisStr.find(ntcmdErrStr) != -1 or len(netstatLisStr) < 1:
                nsStrOk = 'false'
            elif re.search('\r\n', netstatLisStr):
                nsLisLines = netstatLisStr.split('\r\n')
                nsStrOk = 'true'
            elif re.search('\n', netstatLisStr):
                nsLisLines = netstatLisStr.split('\n')
                nsStrOk = 'true'
            if nsStrOk == 'true':
                for line in nsLisLines:
                    line = line.strip()
                    m = re.search('\S+\s+(\d+.\d+.\d+.\d+):(\d+)\s+\d+.\d+.\d+.\d+:\d+\s+\S+\s+(\d+).*', line)
                    if (m):
                        ipAddress = m.group(1).strip()
                        ## Skip loopback IPs
                        if re.search('127.0.0', ipAddress):
                            continue
                        ## Set the IP address to that of the destination if it is "*", "::", or "0.0.0.0"
                        ipAddress = dbconnect_utils.fixIP(ipAddress, localClient.getIpAddress())
                        serverPort = m.group(2).strip()
                        pid = m.group(3)
                        dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Got port <%s> for pid <%s>' % (serverPort, pid))

                        # modified if statement slightly to include check to see if listener is listening on port 80, 2481, or 2482. If so, these can be ignored. - Daniel La
                        if pid != '-' and procToPortDict.has_key(pid) and not (serverPort in ['80', '2481', '2482'] and re.search('tns', (procToPortDict[pid])[0].lower())):


                            dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Adding port <%s:%s> for process <%s>' % (ipAddress, serverPort, (procToPortDict[pid])[0]))

                            (procToPortDict[pid])[dbconnect_utils.IP_INDEX] = ipAddress
                            (procToPortDict[pid])[dbconnect_utils.PORT_INDEX] = serverPort
                            # create new key and add new entry - Daniel La
                            pidnport = str(pid) + '.' + str(serverPort)
                            if dbconnect_utils.populateProcToPortDict(procToPortDict, pidnport, (procToPortDict[pid])[dbconnect_utils.PROCESSNAME_INDEX], (procToPortDict[pid])[dbconnect_utils.PORT_INDEX], (procToPortDict[pid])[dbconnect_utils.IP_INDEX], (procToPortDict[pid])[dbconnect_utils.PATH_INDEX], (procToPortDict[pid])[dbconnect_utils.VERSION_INDEX], (procToPortDict[pid])[dbconnect_utils.STATUS_INDEX], (procToPortDict[pid])[dbconnect_utils.COMMANDLINE_INDEX], (procToPortDict[pid])[dbconnect_utils.USER_INDEX]) == 0:
                                logger.debug('Unable to add ', (procToPortDict[pid])[dbconnect_utils.PROCESSNAME_INDEX])
                            else:
                                # add key to list of keys to delete later as we've updated them with new entries.
                                keydeletion.append(pid)
                        dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Got port <%s> for pid <%s>' % (serverPort, pid))
                    else:
                        dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Couldn\'t get process information (Most likely due to lack of user permissions): ' + line)
                # delete keys which are of no value anymore - Daniel La
                for key in keydeletion:
                    if procToPortDict.has_key(key):
                        del procToPortDict[key]
                        logger.debug('deleted key: ', key)
            else:
                dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Invalid output from netstat: <%s>' % netstatLisStr)
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to make a process to port map using netstat: <%s>' % excInfo)
            pass

        ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Returning process to port dictionary with <%s> items' % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Returning EMPTY process to port dictionary')
            return None
    except:
        excInfo = logger.prepareJythonStackTrace('')
        dbconnect_utils.debugPrint('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Exception: <%s>' % excInfo)
        pass
コード例 #11
0
def getProcListByWMI(localClient, wmiRegistryClient):
	try:
		dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcListByWMI]')
		procToPortDict = {}
		HOST_IP = localClient.getIpAddress()

		## Not using WMI HR scripts since they are not split into a main discovery and
		## utils script. Using them will result in those discoveries being executed for
		## this destination and host resource data will be added to the CMDB

		## Get a list of processes
		try:
			resultSet = localClient.executeQuery('SELECT name, processid, executablepath, commandline FROM Win32_Process')
			while resultSet.next():
				## Name
				processName = resultSet.getString(1).strip()
				if processName == None or processName == '' or len(processName) <1:
					## We don't care about nameless processes
					continue
				pid = resultSet.getString(2).strip()				## PID
				processPath = resultSet.getString(3).strip()		## Path
				processPath = string.replace(processPath, '"', '')
				processCmdline = resultSet.getString(4).strip()	## Command line
				processCmdline = string.replace(processCmdline, '"', '')
				## Add this to the dictionary
				dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcListByWMI] Got PROCESS <%s:%s> with path <%s> and command line <%s>' % (pid, processName, processPath, processCmdline))
				## {PID:[processName, listeningPort, ipAddress, path, version, status, processCommandline]}
#				procToPortDict[pid] = [processName, dbconnect_utils.UNKNOWN, HOST_IP, processPath, dbconnect_utils.UNKNOWN, 'Running', processCmdline]
				if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, processName, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, processPath, dbconnect_utils.UNKNOWN, 'Running', processCmdline) == 0:
					logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s> and command line <%s> to the procToPort dictionary' % (pid, processName, 'Running', processPath, processCmdline))
		except:
			excInfo = logger.prepareJythonStackTrace('')
			logger.debug('[' + SCRIPT_NAME + ':getProcListByWMI] Unable to get a list of proceses: <%s>' % excInfo)
			pass

		## Get a list of services
		try:
			resultSet = localClient.executeQuery('SELECT displayname, processid, pathname, started FROM Win32_Service')
			fakePid = 0
			while resultSet.next():
				## Name
				serviceName = resultSet.getString(1).strip()
				if serviceName == None or serviceName == '' or len(serviceName) <1:
					## We don't care about nameless services
					continue
				pid = resultSet.getString(2).strip()				## PID
				if pid == '0':
					pid = 'SERVICE ' + str(fakePid)
					fakePid = fakePid + 1
					dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcListByWMI] Using fake PID <%s> for service <%s>' % (pid, serviceName))
				servicePath = resultSet.getString(3).strip()		## Path
				servicePath = string.replace(servicePath, '"', '')
				serviceStatus = resultSet.getString(4).strip()	## Status
				if serviceStatus.lower() == 'true':
					serviceStatus = 'Running'
				else:
					serviceStatus = 'Not Running'
				serviceCmdline = servicePath
				## Add this to the dictionary
				dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcListByWMI] Got SERVICE <%s:%s> (%s) with path <%s> and command line <%s>' % (pid, serviceName, serviceStatus, servicePath, serviceCmdline))
				## {PID:[serviceName, listeningPort, ipAddress, path, version, status, processCommandline]}
#				procToPortDict[pid] = [serviceName, dbconnect_utils.UNKNOWN, HOST_IP, servicePath, dbconnect_utils.UNKNOWN, serviceStatus, serviceCmdline]
				if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, serviceName, dbconnect_utils.UNKNOWN, HOST_IP, servicePath, dbconnect_utils.UNKNOWN, serviceStatus, serviceCmdline) == 0:
					logger.debug('[' + SCRIPT_NAME + ':getProcListByWMI] Unable to add SERVICE <%s:%s> (%s) with path <%s> and command line <%s> to the procToPort dictionary' % (pid, serviceName, serviceStatus, servicePath, serviceCmdline))
		except:
			excInfo = logger.prepareJythonStackTrace('')
			logger.debug('[' + SCRIPT_NAME + ':getProcListByWMI] Unable to get a list of services: <%s>' % excInfo)
			pass

		## Get a list of installed software
		try:
			fakePid = 0
			regKeypath = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
			swNames = dbconnect_utils.getRegValues(localClient, wmiRegistryClient, regKeypath, 'DisplayName')
			swPaths = dbconnect_utils.getRegValues(localClient, wmiRegistryClient, regKeypath, 'UninstallString')
			swVersions = dbconnect_utils.getRegValues(localClient, wmiRegistryClient, regKeypath, 'DisplayVersion')
			for swName in swNames.keys():
				swName = swNames.get(swName)
				swPath = swPaths.get(swName)
				swVersion = swVersions.get(swName)
				pid = 'SOFTWARE ' + str(fakePid)
				fakePid = fakePid + 1
				## Add this to the dictionary
				dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcListByWMI] Got SOFTWARE <%s:%s> with path <%s> and version <%s>' % (pid, swName, swPath, swVersion))
				## {PID:[serviceName, listeningPort, ipAddress, path, version, status, processCommandline]}
				if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, swName, dbconnect_utils.UNKNOWN, HOST_IP, swPath, swVersion, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN) == 0:
					logger.debug('[' + SCRIPT_NAME + ':getProcListByWMI] Unable to add SOFTWARE <%s:%s> with path <%s> and version <%s>' % (pid, swName, swPath, swVersion))
		except:
			excInfo = logger.prepareJythonStackTrace('')
			logger.debug('[' + SCRIPT_NAME + ':getProcListByWMI] Unable to get a list of software: <%s>' % excInfo)
			pass

		## Should have proc to port map
		if len(procToPortDict) > 0:
			dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcListByWMI] Returning process to port dictionary with <%s> items' % len(procToPortDict))
			return procToPortDict
		else:
			dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcListByWMI] Returning EMPTY process to port dictionary')
			return None
	except:
		excInfo = logger.prepareJythonStackTrace('')
		dbconnect_utils.debugPrint('[' + SCRIPT_NAME + ':getProcListByWMI] Exception: <%s>' % excInfo)
		pass
コード例 #12
0
def getProcToPortDictOnHPUX(localClient, USE_SUDO, USE_LSOF):
    try:
        dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX]')
        procToPortDict = {}

        ## Get process OSHs
        ############################################
        try:
            psOut = localClient.executeCmd('ps -ef')
            psLines = dbconnect_utils.splitCommandOutput(psOut.strip())
            if psLines == None:
                logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Unable to get list of processes!')
                return None
            for psLine in psLines:
                ## Reg for processes with args
                res = re.search('(\w+)\s+?(\d+).*\s\d+\:\d\d\s([0-9a-zA-Z_.\[\]\-+:/]+)\s(.*)', psLine)
                if(res):
                    cleanArgs = res.group(4)
                else:
                    ## Reg for processes with no args
                    res = re.search('(\w+)\s+?(\d+).*\s\d+\:\d\d\s([0-9a-zA-Z_.\-+:/]+)', psLine)
                    if(res):
                        cleanArgs = ''
                if(res):
                    commandPath = res.group(3)
                    pid = res.group(2)
                    userName = res.group(1).strip()
                    cleanCommand = ''
                    if commandPath.find('/') == -1:
                        cleanCommand = commandPath
                    else:
                        res2 = re.search('(.*/)([^/]+)', commandPath)
                        if (res2):
                            cleanCommand = res2.group(2)
                        else:
                            continue
                    commandLine = cleanCommand + ' ' + cleanArgs
                    dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Got PROCESS <%s:%s> with path <%s>, owner <%s>, and command line <%s>' % (pid, cleanCommand, commandPath, userName, commandLine))
                    ## {PID:[cleanCommand, listeningPort, ipAddress, path, version, status, processCommandline]}
#						procToPortDict[pid] = [cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine]
                    if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine, userName) == 0:
                        logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s>, owner <%s>, and command line <%s> to the procToPort dictionary' % (pid, cleanCommand, 'Running', commandPath, userName, commandLine))
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Unable to get list of processes: <%s>' % excInfo)
            return None

        ## Use LSOF to map each process to a port and create a dictionary
        ############################################
        handleProcessToPortByLsof(USE_SUDO, localClient, procToPortDict)
        ## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Returning process to port dictionary with <%s> items' % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Returning EMPTY process to port dictionary')
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnHPUX] Exception: <%s>' % excInfo)
        pass
コード例 #13
0
def getProcToPortDictOnSolaris(localClient, USE_SUDO, USE_LSOF):
    try:
        dbconnect_utils.debugPrint(3, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris]')
        procToPortDict = {}

        ## Get process OSHs
        ############################################
        try:
            psCmd = 'ps -e -o pid -o uid -o user -o time -o args'
            if USE_SUDO:
                psCmd = 'sudo ' + psCmd
            psOut = localClient.executeCmd(psCmd)
            psLines = dbconnect_utils.splitCommandOutput(psOut.strip())
            if psLines == None:
                logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Unable to get list of processes!')
                return None
            for line in psLines:
                line = line.strip()
                token=line.split(None,4)
                # Some checks to make sure line is valid
                if (len(token) != 5):
                    continue
                if (not re.search('^\d+$',token[0])):
                    continue
                if (len(token[4]) < 2):
                    continue
                spaceIndex = token[4].find(' ')
                commandPath = ''
                cleanArgs = ''
                if spaceIndex > -1:
                    commandPath = token[4][:spaceIndex]
                    try:
                        cleanArgs = token[4][spaceIndex+1:]
                    except:
                        cleanArgs = ''
                else:
                    commandPath = token[4]
                    cleanArgs = ''
                pid = token[0]
                userName = token[2]
                cleanCommand = ''
                cleanPath = ''
                if (commandPath.find('/') == -1) or (commandPath[0] == '['):
                    cleanCommand = commandPath
                    cleanPath = ''
                else:
                    res2 = re.search('(.*/)([^/]+)', commandPath)
                    if (res2):
                        cleanPath = res2.group(1)
                        cleanCommand = res2.group(2)
                    else:
                        continue
                commandLine = cleanCommand + ' ' + cleanArgs
                dbconnect_utils.debugPrint(4, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Got PROCESS <%s:%s> with path <%s>, owner <%s>, and command line <%s>' % (pid, cleanCommand, commandPath, userName, commandLine))
                ## {PID:[cleanCommand, listeningPort, ipAddress, path, version, status, processCommandline]}
#						procToPortDict[pid] = [cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine]
                if dbconnect_utils.populateProcToPortDict(procToPortDict, pid, cleanCommand, dbconnect_utils.UNKNOWN, dbconnect_utils.UNKNOWN, commandPath, dbconnect_utils.UNKNOWN, 'Running', commandLine, userName) == 0:
                    logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnWindows] Unable to add PROCESS <%s:%s> (%s) with path <%s>, owner <%s>, and command line <%s> to the procToPort dictionary' % (pid, cleanCommand, 'Running', commandPath, userName, commandLine))
        except:
            excInfo = logger.prepareJythonStackTrace('')
            logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Unable to get list of processes: <%s>' % excInfo)
            return None
        allowPFiles = getGlobalSetting().getPropertyBooleanValue('allowPFilesOnSunOS', False)
        if USE_LSOF:
            handleProcessToPortByLsof(USE_SUDO, localClient, procToPortDict)
        elif allowPFiles:
            handleProcessToPortByPFile(USE_SUDO, localClient, procToPortDict)## Should have proc to port map
        if len(procToPortDict) > 0:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Returning process to port dictionary with <%s> items' % len(procToPortDict))
            return procToPortDict
        else:
            dbconnect_utils.debugPrint(2, '[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Returning EMPTY process to port dictionary')
            return None
    except:
        #excInfo = str(sys.exc_info()[1])
        excInfo = logger.prepareJythonStackTrace('')
        logger.debug('[' + SCRIPT_NAME + ':getProcToPortDictOnSolaris] Exception: <%s>' % excInfo)
        pass