Exemple #1
0
    def collectData(self):
        """Collect disk usage data.
        """

        self.data.datahash = {}
        self.data.mounthash = {}

        drives = win32perf.getDriveNames(filter=(win32perf.DRIVE_FIXED,
                                                 win32perf.DRIVE_REMOVABLE))
        drives = [d[:-1] for d in drives
                  if d not in ('A:\\', 'B:\\')]  # remove '\'; ignore A: & B:

        for fs in drives:
            try:
                fsinfo = win32file.GetDiskFreeSpace(fs + '\\')
            except pywintypes.error, err:
                log.log(
                    "<df>dfList.collectData(): pywintypes.error, %s" % (err),
                    7)
                continue  # skip invalid drives
            assert len(fsinfo) == 4
            p = df(fs, fsinfo)
            self.data.datahash[fs] = p  # dictionary of filesystem devices
            self.data.mounthash[
                fs] = p  # dictionary of mount points (hmm, same)
Exemple #2
0
    def collectData(self):
        """Collect process list.
        """

        self.data.datahash = {}                # dict of processes keyed by pid
        self.data.proclist = []                # list of processes
        self.data.nameHash = {}                # dict of processes keyed by process name

        procs = win32process.EnumProcesses()

        for pid in procs:
            try:
                han = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION|win32con.PROCESS_VM_READ, 0, pid)
            except:
                # privileges may prevent querying the process details
                han = None
            p = proc(pid, han)

            if han:
                han.Close()

            self.data.proclist.append(p)
            self.data.datahash[p.pid] = p
            self.data.nameHash[p.procname] = p

        log.log( "<proc>procList.collectData(): new proc list created", 7 )
    def getData(self):
        """
        Called by Directive docheck() method to fetch the data required for
        evaluating the directive rule.
        """

        datahash = None

        # Get data as directed by rule.
        # * this is hard-coded to a few different 'rules' atm.  This should be
        # cleaned up later to handle any type of rule (TODO)

        if self.args.rule[:6] == 'system':
            datahash = self.data_collectors['system.system'].getHash(
            )  # get dictionary of system stats
        elif self.args.rule[:7] == 'netstat':
            datahash = self.data_collectors['netstat.stats_ctrs'].getHash(
            )  # get dictionary of network stats
        elif self.args.rule[:4] == 'proc':
            datahash = self.data_collectors['proc.procList'].allprocs(
            )  # get dictionary of process details
        elif self.args.rule[:2] == 'if':
            datahash = self.data_collectors[
                'netstat.netstat'].getAllInterfaces(
                )  # get dictionary of interface details

        if datahash == None:
            log.log(
                "<directive>STORE.getData(): rule '%s' is invalid." %
                (self.args.rule), 4)
            return None

        return datahash
Exemple #4
0
    def collectData(self):

        self.data.datalist = []  # list of tcp objects
        self.data.datahash = {}  # hash of same objects keyed on '<ip>:<port>'
        self.data.numconnections = 0

        # get the tcp stats
        rawList = utils.safe_popen('/usr/bin/netstat -anf inet -p tcp', 'r')

        # skip header lines
        rawList.readline()
        rawList.readline()

        for line in rawList.readlines():
            f = string.split(line)

            if len(f) != 6:
                continue  # should be 6 fields per line

            t = tcp(f)  # new tcp instance

            self.data.datalist.append(t)
            self.data.datahash['%s:%s' %
                               (t.local_addr_ip, t.local_addr_port)] = t

            self.data.numconnections = self.data.numconnections + 1

        utils.safe_pclose(rawList)

        log.log(
            "<netstat>TCPtable.collectData(): Collected %d TCP connections" %
            (self.data.numconnections), 6)
def agent():
    try:
        main()

    except parseConfig.ConfigError:
        sys.exit(1)

    except:  # catch any uncaught exceptions so we can log them
        e = sys.exc_info()
        import exceptions
        if e[0] != exceptions.SystemExit:
            import traceback
            tb = traceback.format_list(traceback.extract_tb(e[2]))
            import string
            tbstr = string.join(tb, '')
            log.log(
                "<eddie.py>: EDDIE died with exception: %s, %s\n%s" %
                (e[0], e[1], tbstr), 1)
            log.sendadminlog()
            sys.stderr.write("EDDIE died with exception:")
            sys.stderr.write(tbstr + '\n')
            sys.stderr.write(str(e[0]) + '\n' + str(e[1]) + '\n')
            sys.exit(1)

    # email admin anything else...
    log.sendadminlog()
Exemple #6
0
    def collectData(self):

        self.data.datalist = []  # list of tcp objects
        self.data.datahash = {}  # hash of same objects keyed on '<ip>:<port>'
        self.data.numconnections = 0

        # get the udp stats
        rawList = utils.safe_popen('netstat -anf inet | grep ^udp', 'r')

        for line in rawList.readlines():
            f = string.split(line)

            if len(f) != 5:
                continue  # should be 2 fields per line

            t = udp(f)  # new udp instance

            self.data.datalist.append(t)
            self.data.datahash['%s:%s' %
                               (t.local_addr_ip, t.local_addr_port)] = t

            self.data.numconnections = self.data.numconnections + 1

        utils.safe_pclose(rawList)

        log.log(
            "<netstat>UDPtable.collectData(): Collected %d UDP connections" %
            (self.data.numconnections), 6)
Exemple #7
0
    def collectData(self):
        """Collect network interface data.
        """

        self.data.datahash = {}  # hash of same objects keyed on interface name
        self.data.numinterfaces = 0

        # get the interface stats
        rawList = utils.safe_popen('/usr/bin/netstat -in', 'r')

        # skip header line
        rawList.readline()

        for line in rawList.readlines():
            f = string.split(line)

            if len(f) != 9:
                continue  # should be 9 fields per line

            if string.find(f[2], "Link") == -1:
                continue  # only want real interfaces

            t = interface(f)  # new interface instance

            self.data.datahash[t.name] = t

            self.data.numinterfaces = self.data.numinterfaces + 1

        utils.safe_pclose(rawList)

        log.log(
            "<netstat>IntTable.collectData(): Collected data for %d interfaces"
            % (self.data.numinterfaces), 6)
    def tokenparser(self, toklist, toktypes, indent):
        """Parse tokenized input."""

        apply(directive.Directive.tokenparser,
              (self, toklist, toktypes, indent))

        # test required arguments
        try:
            self.args.name
        except AttributeError:
            raise directive.ParseFailure, "Process name not specified"
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure, "Rule not specified"

        # Set any PROC-specific action variables
        #  proc_check_name = the process name being checked
        self.defaultVarDict['name'] = self.args.name

        # define the unique ID
        if self.ID == None:
            self.ID = '%s.PROC.%s' % (log.hostname, self.args.name)
        self.state.ID = self.ID

        log.log(
            "<directive>PROC.tokenparser(): ID '%s' name '%s' rule '%s'" %
            (self.state.ID, self.args.name, self.args.rule), 8)
    def getData(self):

        if self.args.protocol == 'tcp' or self.args.protocol == 'TCP':
            connections = self.data_collectors['netstat.TCPtable'].getHash()
        elif self.args.protocol == 'udp' or self.args.protocol == 'UDP':
            connections = self.data_collectors['netstat.UDPtable'].getHash()
        else:
            log.log(
                "<directive>SP.getData(): protocol '%s' illegal" %
                (self.args.protocol), 8)
            raise directive.DirectiveError, "protocol '%s' illegal" % (
                self.args.protocol)

        if len(connections) == 0:
            log.log(
                "<directive>SP.getData(): Zero connections for protocol '%s'" %
                (self.args.protocol), 6)
            return None

        data = {}
        if self.args.bindaddr == 'any':
            # only compare port part of connection - ignore bind address
            data['exists'] = False
            for key in connections.keys():
                p = key.split(':')[1]
                if p == str(self.port):
                    data['exists'] = True
                    break
        else:
            # compare bind address and port for match
            key = "%s:%s" % (self.args.bindaddr, self.port)
            data['exists'] = key in connections.keys()  # true or false

        return data
    def collectData(self):
        """Collect process list.
        """

        self.data.datahash = {}  # dict of processes keyed by pid
        self.data.proclist = []  # list of processes
        self.data.nameHash = {}  # dict of processes keyed by process name

        #rawList = utils.safe_popen('/usr/bin/ps -e -o "s user ruser group rgroup uid ruid gid rgid pid ppid pgid sid pri opri pcpu pmem vsz rss osz time etime stime f c tty addr nice class wchan fname comm args"', 'r')
        rawList = utils.safe_popen(
            '/bin/ps -axwww -o "state user ruser uid ruid rgid pid ppid pgid pri pcpu pmem vsz rss time f tty nice wchan ucomm command"',
            'r')
        rawList.readline()  # skip header

        for line in rawList.readlines():
            try:
                p = proc(line)
            except:
                e = sys.exc_info()
                log.log(
                    "<proc>procList.collectData(): exception parsing proc: %s, %s; line: %s"
                    % (e[0], e[1], line), 5)
            else:
                self.data.proclist.append(p)
                self.data.datahash[p.pid] = p
                self.data.nameHash[p.procname] = p

        utils.safe_pclose(rawList)

        log.log("<proc>procList.collectData(): new proc list created", 7)
    def tokenparser(self, toklist, toktypes, indent):
        apply(directive.Directive.tokenparser,
              (self, toklist, toktypes, indent))

        # test required arguments
        try:
            self.args.pidfile
        except AttributeError:
            raise directive.ParseFailure, "pidfile argument not specified"
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure, "Rule not specified"

        # Set any PID-specific variables
        #  %pidf = the PID-file
        self.defaultVarDict['pidfile'] = self.args.pidfile
        self.defaultVarDict['rule'] = self.args.rule

        # define the unique ID
        if self.ID == None:
            self.ID = '%s.PID.%s.%s' % (log.hostname, self.args.pidfile,
                                        self.args.rule)
        self.state.ID = self.ID

        log.log(
            "<directive>PID.tokenparser(): ID '%s' pid '%s' rule '%s'" %
            (self.state.ID, self.args.pidfile, self.args.rule), 8)
    def collectData(self):
        """Collect disk usage data.
        """

        # List all local filesystems
        # Note: we don't bother with NFS filesystems at this point.
        # TODO: allow user-specified filesystem types
        rawList = utils.safe_popen('/bin/df -l -k', 'r')

        self.data.datahash = {}
        self.data.mounthash = {}

        # skip header line
        rawList.readline()

        for line in rawList.readlines():
            fields = string.split(line)
            p = df(fields)
            self.data.datahash[
                fields[0]] = p  # dictionary of filesystem devices
            self.data.mounthash[fields[5]] = p  # dictionary of mount points

        utils.safe_pclose(rawList)

        log.log(
            "<df>dfList.collectData(): collected data for %d filesystems" %
            (len(self.data.datahash.keys())), 6)
Exemple #13
0
    def collectData(self):
        """Collect disk usage data.
        """

        dfre = "^([/0-9a-zA-Z]+)\s*\(([/0-9a-zA-Z])\s*\)\s*:\s*([0-9]+)\s*total allocated Kb\s*([0-9]+)\s*free allocated Kb\s*([0-9]+)\s*used allocated Kb\s*([0-9]+)\s*% allocation used"

        rawList = utils.safe_popen('df -ktffs', 'r')
        rawList.readline()  # skip header

        self.data.datahash = {}  # dict of filesystems keyed by device
        self.data.mounthash = {}  # dict of filesystems keyed by mount point

        prevline = None
        for line in rawList.readlines():
            if prevline:
                line = prevline + " " + line  # join any previous line to current
                prevline = None
            fields = string.split(line)
            if len(fields) == 1:  # if 1 field, assume rest on next line
                prevline = line
                continue
            p = df(fields)
            self.data.datahash[fields[0]] = p  # dict of filesystem devices
            self.data.mounthash[fields[5]] = p  # dict of mount points
            prevline = None

        utils.safe_pclose(rawList)

        log.log(
            "<df>dfList.collectData(): collected data for %d filesystems" %
            (len(self.data.datahash.keys())), 6)
Exemple #14
0
    def collectData(self):
        """
        Collect process list.
        """

        self.data.datahash = {}                # dict of processes keyed by pid
        self.data.proclist = []                # list of processes
        self.data.nameHash = {}                # dict of processes keyed by process name

        # TODO: read process info from /proc instead of parsing 'ps' output...
        #rawList = utils.safe_popen('ps -e -o "s user ruser group rgroup uid ruid gid rgid pid ppid pgid sid pri opri pcpu pmem vsz rss osz time etime stime f c tty addr nice class wchan fname comm args"', 'r')
        # remove wchan field - it sometimes causes kernel warnings
        rawList = utils.safe_popen('ps -e -o s,user,ruser,group,rgroup,uid,ruid,gid,rgid,pid,ppid,pgid,sid,pri,opri,pcpu,pmem,vsz,rss,osz,time,etime,stime,f,c,tty,addr,nice,class,fname,comm,args', 'r')
        rawList.readline()
 
        for line in rawList.readlines():
            p = proc(line)
            self.data.proclist.append(p)
            self.data.datahash[p.pid] = p
            #self.data.nameHash[string.split(p.comm, '/')[-1]] = p
            self.data.nameHash[string.split(p.procname, '/')[-1]] = p

        utils.safe_pclose( rawList )

        log.log( "<proc>procList.collectData(): new process list created", 7 )
    def parse_prtdiag_serverblade1(self):
        """Parse prtdiag output of a Sun Blade server (type 1).
        Not sure what other types are yet.
        """

        prtdiag = "/usr/platform/SUNW,Serverblade1/sbin/prtdiag"
        try:
            os.stat(prtdiag)
        except:
            log.log(
                "<solaris>PRTDIAG.parse_prtdiag_serverblade1(): %s not found, directive cancelled"
                % (prtdiag), 4)
            return None

        cmd = "%s -v" % (prtdiag)
        (retval, output) = utils.safe_getstatusoutput(cmd)

        prtdiag_dict = {}
        prtdiag_dict['die_temp'] = None
        prtdiag_dict['die_status'] = None
        prtdiag_dict['ambient_temp'] = None
        prtdiag_dict['ambient_status'] = None
        prtdiag_dict['cpu_fan'] = None

        for line in output.split('\n'):
            if line.startswith('Blade/CPU0 Die'):
                prtdiag_dict['die_temp'] = int(line.split()[2][:-1])
                prtdiag_dict['die_status'] = line.split()[-1]
            if line.startswith('Blade/CPU0 Ambient'):
                prtdiag_dict['ambient_temp'] = int(line.split()[2][:-1])
                prtdiag_dict['ambient_status'] = line.split()[-1]
            if line.startswith('Blade/cpu-fan'):
                prtdiag_dict['cpu_fan'] = line.split()[-1]

        return prtdiag_dict
    def tokenparser(self, toklist, toktypes, indent):
        apply(directive.Directive.tokenparser,
              (self, toklist, toktypes, indent))

        # test required arguments
        try:
            self.args.cmd
        except AttributeError:
            raise directive.ParseFailure, "Command (cmd) not specified"
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure, "Rule not specified"

        # Set any COM-specific variables
        #  cmd = the command
        self.defaultVarDict['cmd'] = self.args.cmd

        # define the unique ID
        if self.ID == None:
            self.ID = '%s.COM.%s.%s' % (log.hostname, self.args.cmd,
                                        self.args.rule)
        self.state.ID = self.ID

        log.log(
            "<directive>COM.tokenparser(): ID '%s' cmd '%s' rule '%s'" %
            (self.state.ID, self.args.cmd, self.args.rule), 8)
    def collectData(self):
        """Collect process list.
        """

        self.data.datahash = {}  # dict of processes keyed by pid
        self.data.proclist = []  # list of processes
        self.data.nameHash = {}  # dict of processes keyed by process name

        procs = win32process.EnumProcesses()

        for pid in procs:
            try:
                han = win32api.OpenProcess(
                    win32con.PROCESS_QUERY_INFORMATION
                    | win32con.PROCESS_VM_READ, 0, pid)
            except:
                # privileges may prevent querying the process details
                han = None
            p = proc(pid, han)

            if han:
                han.Close()

            self.data.proclist.append(p)
            self.data.datahash[p.pid] = p
            self.data.nameHash[p.procname] = p

        log.log("<proc>procList.collectData(): new proc list created", 7)
    def tokenparser(self, toklist, toktypes, indent):
        apply(directive.Directive.tokenparser,
              (self, toklist, toktypes, indent))

        # test required arguments
        try:
            self.args.host
        except AttributeError:
            raise directive.ParseFailure, "Host not specified"
        try:
            self.args.port
        except AttributeError:
            raise directive.ParseFailure, "Port not specified"
        try:
            self.args.port = int(self.args.port)
        except ValueError:
            raise directive.ParseFailure, "Port is not an integer: %s" % (
                self.args.port)
##        send is optional
        try:
            self.args.send
        except AttributeError:
            self.args.send = ""  # default to not send


##        expect is optional
#        try:
#            self.args.expect
#        except AttributeError:
#            raise directive.ParseFailure, "Expect string not specified"
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure, "Rule not specified"

        # Set any PORT-specific variables
        #  host = the host
        #  port = the port
        #  send = the send string
        #  expect = the expect string
        self.defaultVarDict['host'] = self.args.host
        self.defaultVarDict['port'] = self.args.port
        self.defaultVarDict['rule'] = self.args.rule
        self.defaultVarDict['send'] = self.args.send
        if 'expect' in dir(self.args):
            self.defaultVarDict['expect'] = self.args.expect

        if 'expectrexp' in dir(self.args):
            self.defaultVarDict['expectrexp'] = self.args.expectrexp
            self.regexp = re.compile(self.args.expectrexp)

        # define the unique ID
        if self.ID == None:
            self.ID = '%s.PORT.%s.%d' % (log.hostname, self.args.host,
                                         self.args.port)
        self.state.ID = self.ID

        log.log(
            "<directive>PORT.tokenparser(): ID '%s' host '%s' port %d" %
            (self.state.ID, self.args.host, self.args.port), 8)
    def _getuptime(self):
        """Get system statistics from the output of the 'uptime' command.
        """

        uptime_cmd = "/usr/bin/uptime"

        (retval, output) = utils.safe_getstatusoutput( uptime_cmd )

        if retval != 0:
            log.log( "<system>system._getuptime(): error calling '%s'"%(uptime_cmd), 5 )
            return None

        uptime_dict = {}

        uptime_re = ".+up (?P<uptime>.+), (?P<users>[0-9]+) users?, load averages: (?P<loadavg1>[0-9.]+) (?P<loadavg5>[0-9.]+) (?P<loadavg15>[0-9.]+)"
        inx = re.compile( uptime_re )
        sre = inx.search( output )
        if sre:
            uptime_dict = sre.groupdict()
        else:
            log.log( "<system>system._getuptime(): could not parse uptime output '%s'"%(output), 5 )
            return None

        # convert types
        uptime_dict['uptime'] = uptime_dict['uptime']
        uptime_dict['users'] = int(uptime_dict['users'])
        uptime_dict['loadavg1'] = float(uptime_dict['loadavg1'])
        uptime_dict['loadavg5'] = float(uptime_dict['loadavg5'])
        uptime_dict['loadavg15'] = float(uptime_dict['loadavg15'])

        return uptime_dict
    def tokenparser(self, toklist, toktypes, indent):
        """Parse rest of rule (after ':')."""
        apply(directive.Directive.tokenparser,
              (self, toklist, toktypes, indent))

        # test required arguments
        try:
            self.args.name
        except AttributeError:
            raise directive.ParseFailure, "Interface name not specified"
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure, "Rule not specified"

        self.defaultVarDict['name'] = self.args.name

        # define the unique ID
        if self.ID == None:
            self.ID = '%s.IF.%s.%s' % (log.hostname, self.args.name, self.rule)
        self.state.ID = self.ID

        log.log(
            "<directive>IF.tokenparser(): ID '%s' name '%s', rule '%s'" %
            (self.state.ID, self.args.name, self.args.rule), 8)
Exemple #21
0
    def collectData(self):
        """Collect network statistics.
        """

        self.data.datahash = {}  # hash of stats

        # get the network stats
        rawList = utils.safe_popen('/usr/bin/netstat -s', 'r')

        # regexp for pulling out stats
        statsre = "\s*([0-9]+)\s*(.*)"
        sre = re.compile(statsre)

        line = rawList.readline()
        while 1:
            if len(line) == 0:
                break
            inx = sre.search(line)
            if inx != None:
                self.data.datahash[inx.group(2)] = long(inx.group(1))
            line = rawList.readline()

        utils.safe_pclose(rawList)

        log.log(
            "<netstat>stats_ctrs.collectData(): Collected %d network counters"
            % (len(self.data.datahash)), 6)
    def tokenparser(self, toklist, toktypes, indent):
        """
        Parse directive arguments.
        """

        apply(directive.Directive.tokenparser,
              (self, toklist, toktypes, indent))

        # test required arguments
        try:
            self.args.fs
        except AttributeError:
            raise directive.ParseFailure, "Filesystem not specified"
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure, "Rule not specified"

        # Set any directive-specific variables
        self.defaultVarDict['rule'] = self.args.rule

        # define the unique ID
        if self.ID == None:
            self.ID = '%s.FS.%s' % (log.hostname, self.args.fs)
        self.state.ID = self.ID

        log.log(
            "<directive>FS.tokenparser(): ID '%s' fs '%s' rule '%s'" %
            (self.state.ID, self.args.fs, self.args.rule), 8)
    def getData(self):
        """
        Perform a Radius authentication and return results.
        """

        timing = None

        # create pop3 connection object
        r = radcm.Radius(self.host, self.args.secret, self.port)
        tstart = time.time()
        try:
            passed = r.authenticate(self.args.user, self.args.password)
        except radcm.NoResponse:
            passed = 0
        tend = time.time()
        timing = tend - tstart

        # Values are set to None if there was some problem performing the
        # commands.
        if timing == None:
            timing = 0
            log.log(
                "<radius>RADIUS.getData(): timing could not be measured, setting to 0",
                5)

        log.log(
            "<radius>RADIUS.getData(): timing=%s passed=%s" % (timing, passed),
            7)

        # assign variables
        data = {}
        data['timing'] = timing
        data['passed'] = passed

        return data
    def tokenparser(self, toklist, toktypes, indent):
        """
        Parse directive arguments.
        """

        apply(directive.Directive.tokenparser,
              (self, toklist, toktypes, indent))

        # test required arguments
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure, "Rule not specified"

        # Rule should be a string
        if type(self.args.rule) != type('STRING'):
            raise directive.ParseFailure, "STORE parse error, rule is not string."

        self.defaultVarDict['rule'] = self.args.rule

        # define the unique ID
        if self.ID == None:
            self.ID = '%s.STORE.%s' % (log.hostname, self.args.rule)
        self.state.ID = self.ID

        log.log(
            "<directive>STORE.tokenparser(): ID '%s' rule '%s'" %
            (self.state.ID, self.args.rule), 8)
Exemple #25
0
    def getData(self):
        """
        The 'check' in this case is to login to the smtp server and
        perform a few actions, recording the timing of each action.
        """

        data = {}

        connecttime = None

        # create smtp connection object
        p = smtpclient(self.host, self.port)
        if p.connect():
            data['connected'] = 1
            connecttime = p.timing
            p.close()
        else:
            data['connected'] = 0

        # assign variables
        data['connecttime'] = connecttime

        log.log("<smtp>SMTP.getData(): connecttime=%s" % connecttime, 7)

        return data
Exemple #26
0
    def _getsysctl(self):
        """Get system statistics from the output of the 'sysctl -a' command.
        """

        sysctl_cmd = "/sbin/sysctl -a"

        (retval, output) = utils.safe_getstatusoutput( sysctl_cmd )

        if retval != 0:
            log.log( "<system>system._getsysctl(): error calling '%s'"%(sysctl_cmd), 5 )
            return None

        fulldict = {}

        for line in string.split( output, '\n' ):
            splitline = string.split( line, ':', 2 )
            if len( splitline ) == 2:
                fulldict[splitline[0]] = splitline[1]

        sysctl_dict = {}

        # CPU counters
        try:
            cp_time = fulldict['kern.cp_time'].split()
            sysctl_dict['ctr_cpu_user'] = long( cp_time[0] )
            sysctl_dict['ctr_cpu_nice'] = long( cp_time[1] )
            sysctl_dict['ctr_cpu_system'] = long( cp_time[2] )
            sysctl_dict['ctr_cpu_interrupt'] = long( cp_time[3] )
            sysctl_dict['ctr_cpu_idle'] = long( cp_time[4] )
        except KeyError, msg:
            # This version of FreeBSD does not support kern.cp_time (old versions do not)
            pass
Exemple #27
0
    def collectData(self):
        self.data.datalist = []                        # list of TCP objects
        self.data.datahash = {}                        # hash of same objects keyed on '<ip>:<port>'
        self.data.numconnections = 0

        # get list of current TCP connections
        rawList = utils.safe_popen('netstat -an -t', 'r')

        # skip header line
        rawList.readline()

        for line in rawList.readlines():
            f = string.split(line)

            if len(f) != 6:
                continue                # should be 7 fields per line

            t = tcp(f)                        # new TCP instance

            self.data.datalist.append(t)
            self.data.datahash['%s:%s' % (t.local_addr_ip,t.local_addr_port)] = t

            self.data.numconnections = self.data.numconnections + 1        # count number of TCP connections

        utils.safe_pclose( rawList )

        log.log( "<netstat>TCPtable.collectData(): Collected %d TCP connections" %(self.data.numconnections), 6 )
    def parse_prtdiag_u280r(self):
        """Parse prtdiag for a U280R."""

        prtdiag = "/usr/platform/sun4u/sbin/prtdiag"

        try:
            os.stat(prtdiag)
        except:
            log.log(
                "<solaris>PRTDIAG.parse_prtdiag_u280r(): %s not found, directive cancelled"
                % (prtdiag), 4)
            return None

        cmd = "%s -v" % (prtdiag)
        (retval, output) = utils.safe_getstatusoutput(cmd)

        # Initialise prtdiag dictionary of values
        prtdiag_dict = {}
        prtdiag_dict['temp_cpu0'] = None
        prtdiag_dict['temp_cpu1'] = None
        prtdiag_dict['failure'] = ""

        inx = re.search("cpu([0-9])\s+([0-9])\s*-+\s*([0-9]+)\s+([0-9]+)",
                        output)
        if inx:  # CPU temps
            prtdiag_dict['temp_cpu%s' % (inx.group(1))] = int(inx.group(3))
            prtdiag_dict['temp_cpu%s' % (inx.group(2))] = int(inx.group(4))

        inx = re.findall("\n(.*?)\s+\[(\w+_FAULT)\]", output)
        for device, fault in inx:
            if fault == 'NO_FAULT':
                continue
            prtdiag_dict['failure'] += "%s: %s " % (device, fault)

        return prtdiag_dict
Exemple #29
0
    def collectData(self):
        """
        Collect network interface data.
        """

        self.data.datahash = {}                # hash of same objects keyed on interface name
        self.data.numinterfaces = 0

        # get the interface statistics
        fp = open('/proc/net/dev', 'r')

        # skip header lines
        fp.readline()
        fp.readline()

        for line in fp.readlines():
            (name,data) = string.split( line, ':' )        # split interface name from data
            f = string.split(data)

            t = interface(f)                # new interface instance
            if t == None:
                log.log( "<netstat>iftable: error parsing interface data for line '%s'"%(line), 5 )
                continue                # could not parse interface data

            t.name = string.strip(name)

            self.data.datahash[t.name] = t

            self.data.numinterfaces = self.data.numinterfaces + 1        # count number of interfaces

        fp.close()

        log.log( "<netstat>IntTable.collectData(): Collected data for %d interfaces" %(self.data.numinterfaces), 6 )
Exemple #30
0
    def collectData(self):
        """
        Collect network statistics.
        """

        self.data.datahash = {}  # hash of stats

        # get the network stats
        rawList = utils.safe_popen('netstat -s', 'r')

        # regexp for pulling out stats
        udpre = "\s*(\w+)\s*=\s*([-0-9]+)(.*)"
        sre = re.compile(udpre)

        line = rawList.readline()
        while 1:
            inx = sre.search(line)
            if inx == None:
                #log.log("<netstat>stats_ctrs: getting udp stats, no re match for line '%s'" % (line), 9)
                line = rawList.readline()
                if len(line) == 0:
                    break
            else:
                self.data.datahash[inx.group(1)] = long(inx.group(2))
                line = inx.group(3)

        utils.safe_pclose(rawList)

        log.log(
            "<netstat>stats_ctrs.collectData(): Collected %d network counters"
            % (len(self.data.datahash)), 6)
Exemple #31
0
    def collectData(self):

        self.data.datalist = []                        # list of UDP objects
        self.data.datahash = {}                        # hash of same objects keyed on '<ip>:<port>'
        self.data.numconnections = 0

        # get the UDP stats
        rawList = utils.safe_popen('netstat -anA inet -u', 'r')

        # skip header lines (2)
        rawList.readline()
        rawList.readline()

        for line in rawList.readlines():
            f = string.split(line)

            if len(f) < 5 or len(f) > 6:
                continue                # should be 5 or 6 fields per line

            t = udp(f)                        # new udp instance

            self.data.datalist.append(t)
            self.data.datahash['%s:%s' % (t.local_addr_ip,t.local_addr_port)] = t

            self.data.numconnections = self.data.numconnections + 1        # count number of UDP connections

        utils.safe_pclose( rawList )

        log.log( "<netstat>UDPtable.collectData(): Collected %d UDP connections" %(self.data.numconnections), 6 )
Exemple #32
0
    def __init__(self, pid, han):

        if han:
            try:
                exe = win32process.GetModuleFileNameEx(han, 0)
            except pywintypes.error, msg:
                if msg[0] != 299 : # we keep getting this error for some reason..?
                    # Error is "Only part of a ReadProcessMemory or WriteProcessMemory request was completed."
                    log.log( "<proc>proc.__init__(): failed win32process.GetModuleFileNameEx(), %s" %(msg), 5 )
                exe = "<unknown>"