Python Script to remotely check, at linux command line, using snmp, the cpu, memory, and cps

Home

There are a number of ways to monitor, or view the cpu, memory, and cps (calls per second) of SBC. You can run commands, on the sbc cli itself, such as 'show platform cpu-load', or 'show memory', and for cps you can run 'show sipd invite', then divide the seconds in time frame by the number of invites. You can also setup HDR records, and view the information that way. Or you can configure a monitoring system to view cpu and memory.
The script below will obtain the current cpu, memory, and cps off SBC using snmp. The one below, will, 3 times, obtain the information, at 5 seconds interval, when run remotely on a linux os.
You must specify, in a text file, the snmp information to use, and the system to monitor (in the script below, the text file is referred to as ssnmp84.txt). The information in the text file is to the right:

[system_84] description=SD-4500-84-1-ETC address=10.13.24.84 port=161 communityro=mysbc84

[check_1] description=AP_PERCENT_CPU_UTIL oid=1.3.6.1.4.1.9148.3.2.1.1.1.0 system=system_84 sampling_rate=10

[check_2] description=AP_PERCENT_MEM_UTIL oid=1.3.6.1.4.1.9148.3.2.1.1.2.0 system=system_84 sampling_rate=10

[check_3] description=AP_GLOBAL_CPS oid=1.3.6.1.4.1.9148.3.2.1.1.6.0 system=system_84 sampling_rate=10

[check_4] description=AP_SYS_UNTRUST_TO_DENY_MSGS oid=1.3.6.1.4.1.9148.3.2.1.1.20.0 system=system_84 sampling_rate=10


#!/usr/bin/python

# Adapted from Pro Python Administration  - Rytis Sileika
import sys,os.path
import time
import datetime
from time import strftime as date
from ConfigParser import SafeConfigParser
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.proto import rfc1902

def time_execution(code):
    start = time.clock() # time.clock is processor time in seconds
    print "start: ", start
    result = eval(code) # allow to evaluate any string as if a python expression
    run_time = time.clock() - start
    return result, run_time


class SnmpManager:
    def __init__(self):
        self.systems = {}
        self.databases_initialised = False

    def add_system(self,id,descr,addr,port,comm_ro):
        self.systems[id] = {'description' : descr,
                            'address'     : addr,
                            'port'        : int(port),
                            'communityro' : comm_ro,
                            'checks'      : {}
                           }

    def add_check(self,id,oid,descr,system,sampling_rate):
        oid_tuple = tuple([int(i) for i in oid.split('.')])
        self.systems[system]['checks'][id] = {'description' : descr,
                                              'oid'         : oid_tuple,
                                              'result'      : None,
                                              'sampling_rate' : sampling_rate
                                             }

    def show_systems(self):
        #id=0
        for key,value in self.systems.iteritems():
            print key,value
            print "\n"
            #id = id + 1

    def query_all_systems(self):
        #outfile = open('/home/users/tlucciano/SNMP_DIR/snmpData_84.txt','a',0)
        outfile = open('/home/users/tlucciano/SNMP_DIR/snmpData_84.txt','a',0)
        outfile.write(" CPU\tMEM\tCPS\tUNT_TO_DENY\t\n")
        if not self.databases_initialised:
            self.initialise_databases()
            self.databases_initialised = True
        cg = cmdgen.CommandGenerator()
        for system in self.systems.values():
            today = datetime.date.today()
            comm_data = cmdgen.CommunityData('my-manager', system['communityro'])
            transport = cmdgen.UdpTransportTarget((system['address'],system['port']))

        #dateNow = date('%Y-%m-%d %H:%M:%S')
        #outfile.write (system['description'] )  ,
        #outfile.write (check['description'] ),
        #outfile.write (" " )  ,

            for key, check in system['checks'].iteritems():
                oid = check['oid']
                errInd,errStatus,errIdx,result = cg.getCmd(comm_data,transport,oid)
                if not errInd and not errStatus:
                    file_name = "%s.rrd" % key
                    print "%s/%s -> %s" % (system['description'],
                                           check['description'],
                                           str(result[0][1]))
                    #print today
                    #print time.time()
                    #print datetime.datetime.now()
                    #outfile.write (" " )  ,
                    #print("VALUE: "),
                    print(str(result[0][1]))
                    outfile.write (str(result[0][1])),
                    outfile.write ("\t " )  ,
                    #outfile.write (dateNow),
            outfile.write ("\n")

    def initialise_databases(self):
        for system in self.systems.values():
            for check in system['checks']:
                data_file = "%s.rrd" % check
                if not os.path.isfile(data_file):
                    print data_file, 'does not exist'




def main(conf_file="ssnmp84.txt"):
    checkCount=0
    if not conf_file:
        print "no config file. exiting"
        sys.exit(-1)
    else:
        print "Reading file %s " % (conf_file)
    config = SafeConfigParser()
    config.read(conf_file)
    #print("config: ", config)
    snmp_manager = SnmpManager()

    for system in [s for s in config.sections() if s.startswith('system')]:
        print(system)
        snmp_manager.add_system(system,
                                config.get(system, 'description'),
                                config.get(system, 'address'),
                                config.get(system, 'port'),
                                config.get(system, 'communityro'))
    for check in [c for c in config.sections() if c.startswith('check')]:
        snmp_manager.add_check(check,
                                config.get(check,'oid'),
                                config.get(check,'description'),
                                config.get(check,'system'),
                                config.get(check, 'sampling_rate'))

    while checkCount < 3:
        snmp_manager.query_all_systems()
        checkCount=checkCount + 1
        os.system('tail -n 2 snmpData_84.txt')
        time.sleep(5)

    #snmp_manager.query_all_systems()
    #snmp_manager.show_systems()

if __name__ == '__main__':
    main()