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


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= port=161 communityro=mysbc84

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

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

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

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


# 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.databases_initialised = False

    def add_system(self,id,descr,addr,port,comm_ro):[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('.')])[system]['checks'][id] = {'description' : descr,
                                              'oid'         : oid_tuple,
                                              'result'      : None,
                                              'sampling_rate' : sampling_rate

    def show_systems(self):
        for key,value in
            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.databases_initialised = True
        cg = cmdgen.CommandGenerator()
        for system in
            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'],
                    #print today
                    #print time.time()
                    #outfile.write (" " )  ,
                    #print("VALUE: "),
                    outfile.write (str(result[0][1])),
                    outfile.write ("\t " )  ,
                    #outfile.write (dateNow),
            outfile.write ("\n")

    def initialise_databases(self):
        for system in
            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"):
    if not conf_file:
        print "no config file. exiting"
        print "Reading file %s " % (conf_file)
    config = SafeConfigParser()
    #print("config: ", config)
    snmp_manager = SnmpManager()

    for system in [s for s in config.sections() if s.startswith('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')]:
                                config.get(check, 'sampling_rate'))

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


if __name__ == '__main__':