예제 #1
0
def poll_device(ip, snmp_community, snmp_version, path, interfaces='all'):
    '''Using SNMP, polls single device for ifMIB returning tuple for graphite.
    :param ip: ip of the device
    :type ip: str
    :param snmp_community: SNMP community that allows ifMIB values to be read
    :type snmp_community: str
    :param snmp_version: version of SNMP device supports
    :type snmp_version: int
    :param path: desired graphite path for device
    :type path: str
    :param interfaces: **ifName** of interfaces to poll. Careful because this
                       value can be different even within the same vendor.
                       Cisco ASA will return full iface name while IOS abbrev.
    :type interfaces: list of strings or single str 'all'.
    '''
    TIMESTAMP = int(time.time())
    NULL_IFS = [
        'Nu0',
        'NV0',
        ]
    CARBON_STRINGS = []

    if snmp_version == 2:
        load('SNMPv2-MIB')
        load('IF-MIB')
        try:
            m = Manager(
                host=ip, community=snmp_community, version=snmp_version
                )
        except socket.gaierror, error:
            log.error('SNMP: Error raised for host: %s - %s', ip, error)
예제 #2
0
    def data(self, data=None):
        for i in self.mibs.split(","): load(i)
        self.manager = M(self.ip, self.community, self.version)
        m = self.manager
        d = {}
        d['model'] = str(self.manager.upsIdentModel).strip()
        d['manufacturer'] = str(m.upsIdentManufacturer).strip()
        d['values'] = {}
        d['values']['battery_voltage'] = int(m.upsBatteryVoltage)
        d['values']['battery_current'] = int(m.upsBatteryCurrent)
        d['values']['input_frequency'] = []
        for l in m.upsInputFrequency:
            d['values']['input_frequency'].append(int(m.upsInputFrequency[l]))

        d['values']['input_voltage'] = []
        for l in m.upsInputVoltage:
            d['values']['input_voltage'].append(int(m.upsInputVoltage[l]))

        d['values']['output_current'] = []
        for l in m.upsOutputCurrent:
            d['values']['output_current'].append(int(m.upsOutputCurrent[l]))

        d['values']['output_power'] = []
        for l in m.upsOutputPower:
            d['values']['output_power'].append(int(m.upsOutputPower[l]))

        return d
예제 #3
0
 def has_snmp(self):
     load("SNMPv2-MIB")
     self.snmp = False
     try:
         m = M(host=str(self.host), community=str(self.snmp_group),
               version=2, timeout=2)
         if m.sysName is not None:
             self.snmp = True
     except Exception, e:
         self.has_error("(snmp) " + e.message)
         self.snmp = False
예제 #4
0
    def snmp(hostname, oids, mibs):
        logger.debug(hostname); logger.debug(oids); logger.debug(mibs)
        for mib in mibs:
            snimpy.load(mib)

        try:
            session = snimpy.snmp.Session(hostname, "public", 1)
            session.timeout = 300  # ms
            session.retries = 2
            infos = session.get(*oids)
            snmp_results = NetworkTools.format_snmp_results(infos)
        except:
            snmp_results = NetworkTools.format_empty_result(oids)

        return snmp_results
예제 #5
0
 def get_port_info_table(self):
     """Obtain the Port table"""
     table = {}
     load('IF-MIB')
     with M(host=self.address, community=self.community, version=2) as m:
         for idx in m.ifName:
             name = m.ifName[idx]
             descr = m.ifDescr[idx]
             # snimpy fails when retrieving an empty value
             try:
                 label = m.ifAlias[idx]
             except UnboundLocalError:
                 label = ''
             print('Adding {} {} {} {}'.format(idx, name, descr, label))
             table[int(idx)] = {"name": name, "descr": descr, "label": label}
     return table
예제 #6
0
 def get_mac_table(self):
     """Obtain the MAC table"""
     table = defaultdict(list)
     load('Q-BRIDGE-MIB')
     logger.info('Retrieving MAC table for {}'.format(self.address))
     with M(host=self.address, community=self.community, version=2) as m:
         dbPort = m.dot1qTpFdbPort
         for idx in dbPort:
             vlan, mac = idx
             # snimpy fails when retrieving an empty value
             try:
                 port = int(dbPort[idx])
                 logger.debug('{} {} {}'.format(port, mac, vlan))
                 table[port].append({"vlan": int(vlan), "mac": _normalize_mac(mac)})
             except SNMPException:
                 logger.error('Unable to get port for mac: {} {}'.format(vlan, mac))
     logger.debug('Finished retrieving MAC table for {}'.format(self.address))
     return table
예제 #7
0
def main():
    logging.info('***************************************************************************')
    logging.info('Starting Script')

    #Prepare stats file
    touch(docroot + 'arista_snmp_alarms_current')
    touch(docroot + 'arista_snmp_exclusions')
    os.rename(docroot+'arista_snmp_alarms_current',docroot+'arista_snmp_alarms_previous')
    touch(docroot + 'arista_snmp_alarms_current')

    #Parse previous alarms file and output to log file for debugging
    try:
        logPreviousAlarms()
    except Exception as inst:
        msg = 'Exception occurred while parsing previous alarms file. Exception: {0}'.format(inst)
        logging.warning(msg)

    #Load required MIBs
    load(docroot + "mibs/ENTITY-MIB.my")
    load(docroot + "mibs/SNMPv2-MIB")
    load(docroot + "mibs/ENTITY-SENSOR-MIB.my")
    load(docroot + "mibs/ARISTA-SMI-MIB.mib")
    load(docroot + "mibs/ARISTA-ENTITY-SENSOR.txt")

    script_start = time.time()
    try:
        deviceFile = open(docroot+'arista_devices','r')
        comm = "public"
        ver = 2
        for line in deviceFile:
            if line[0:1] != "#":
                start = time.time()
                hostname = line[:-1]
                queryDevice(hostname,comm,ver)
                end = time.time()
                print '{0} - {1} - {2} sec. {3} total sec.'.format(deviceCount,hostname,(end-start),(end-script_start))
    except Exception as inst:
        msg = 'Exception occurred in main function. Exception = "{0}"'.format(inst)
        logging.warning('MAIN\tERROR\t{0}'.format(msg))

    logging.info('TOTAL\tSTATS\t(Checked,OK,Error) || Temp({1},{2},{3}) || PSU({4},{5},{6}) || FAN({7},{8},{9}) || Other({10},{11},{12}) || Devices({0})'.format(deviceCount,*totalStats))
    logging.info('Script Complete')
예제 #8
0
def main():
    logging.info('***************************************************************************')
    logging.info('Starting Script')
    deviceCount = 0

    #Prepare stats file
    touch(docroot + 'hp_blade_snmp_exclusions')

    #Load required MIBs
    load(docroot + "mibs/SNMPv2-MIB")
    load(docroot + "mibs/CPQHOST.MIB")
    #We need to use a customized CPQRACK-MIB (cpqrack_spot.mib) because of issues in the official MIB. 
    #This script will only work with this version of the MIB. Some unused indices needed
    #to be removed from some object definitions. See https://github.com/vincentbernat/snimpy/issues/12
    #for details.
    load(docroot + "mibs/cpqrack_spot.mib")

    #Check PagerDuty for open incidents
    try:
        getCurrentAlarms()
    except Exception as inst:
        msg = 'Exception occurred while querying PagerDuty for open incidents; Exception = "{0}"'.format(inst)
        logging.warning('PAGER\tERROR\r{0}'.format(msg))

    script_start = time.time()
    try:
        deviceFile = open(docroot+'device_list','r')
        comm = "public"
        ver = 2
        for line in deviceFile:
            if line[0:1] != "#":
                deviceCount += 1
                start = time.time()
                hostname = line[:-1]
                queryDevice(hostname,comm,ver)
                end = time.time()
                print '{0} - {1} - {2} sec. {3} total sec.'.format(deviceCount,hostname,(end-start),(end-script_start))
    except Exception as inst:
        msg = 'Exception occurred in main function. Exception = "{0}"'.format(inst)
        logging.warning('MAIN\tERROR\t{0}'.format(msg))

    logging.info('TOTAL\tSTATS\t(Checked,OK,Error) || Fan({1},{2},{3}) || Temp({4},{5},{6}) || PSU({7},{8},{9}) || Enclosure({10},{11},{12}) || Mgr({13},{14},{15}) || PowerEnc({16},{17},{18}) || Blades({19},{20},{21})|| Devices({0})'.format(deviceCount,*totalStats))
    logging.info('Script Complete')
예제 #9
0
def main():
    logging.info('***************************************************************************')
    logging.info('Starting Script')
    deviceCount = 0

    #Prepare stats file
    touch(docroot + 'riverbed_exclusions')

    #Load required MIBs
    load(docroot + "mibs/SNMPv2-MIB")
    load(docroot + "mibs/riverbed-rbt.mib")
    load(docroot + "mibs/WW-MIB.txt")

    #Check PagerDuty for open incidents
    try:
        getCurrentAlarms()
    except Exception as inst:
        msg = 'Exception occurred while querying PagerDuty for open incidents; Exception = "{0}"'.format(inst)
        logging.warning('PAGER\tERROR\r{0}'.format(msg))

    script_start = time.time()
    try:
        deviceList = ['<Your riverbed device name>']
        comm = "public"
        ver = 2
        for line in deviceList:
            if line[0:1] != "#":
                deviceCount += 1
                start = time.time()
                hostname = line
                queryDevice(hostname,comm,ver)
                end = time.time()
                print '{0} - {1} - {2} sec. {3} total sec.'.format(deviceCount,hostname,(end-start),(end-script_start))
    except Exception as inst:
        msg = 'Exception occurred in main function. Exception = "{0}"'.format(inst)
        logging.warning('MAIN\tERROR\t{0}'.format(msg))

    logging.info('TOTAL\tSTATS\t(Checked,OK,Error) || Health({1},{2},{3}) || Devices({0})'.format(deviceCount,*totalStats))
    logging.info('Script Complete')
예제 #10
0
snmphost = os.getenv('snmphost','127.0.0.1')
snmpcommunity = os.getenv('snmpcommunity')
print (snmpcommunity)
mqtthost = os.getenv('mqtthost','127.0.0.1')
print (mqtthost)
mqttport = os.getenv('mqttport',1883)
print (mqttport)
print (snmphost)




while True:

 load("IF-MIB")
 m = M(host=snmphost, community=snmpcommunity,version = 1)
 ifspeed= m.ifSpeed[2]
 OutOctet1 = m.ifInOctets[2]
 InOctet1 = m.ifOutOctets[2]
 time.sleep(1)
 m = M(host=snmphost, community=snmpcommunity,version = 1)
 OutOctet2 = m.ifInOctets[2]
 InOctet2 = m.ifOutOctets[2]
 upload= float(float(OutOctet2) - float(OutOctet1))*8 
 download=float(float(InOctet2) - float(InOctet1))*8 
 mqttc = mqtt.Client("python_pub")
 print (upload)
 print (download)
 mqttc.connect(mqtthost,mqttport)
 mqttc.publish("bandwidth/up", upload)
예제 #11
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with r4d.  If not, see <http://www.gnu.org/licenses/>.

import logging
import os

from r4d.db import PowerControl
from snimpy.manager import Manager
from snimpy.manager import load

log = logging.getLogger(__name__)

mibpath = os.path.dirname(__file__)
load(os.path.join(mibpath, "GUDEADS-EPC8x-MIB.txt"))


def register(parent):
    log.debug("register " + __name__)
    parent._add_model('pc8210', pc8210)


class pc8210(PowerControl):
    __mapper_args__ = {'polymorphic_identity': 'pc8210'}

    def num_ports(self):
        m = Manager(self.URI, "public", 2)
        return m.epc8portNumber

    def poweron(self, port):
예제 #12
0
	mac = [binascii.b2a_hex(x) for x in list(octet)]
 	 ":".join(mac)
 
def convertIP(octet):
	ip = [str(int(binascii.b2a_hex(x),16)) for x in list(octet)]
	return ".".join(ip)

# ++++++++++++++++++++
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# --------------------	

############## Load MIBs

load("RFC1213-MIB")					# sysName, ecc..
load("IF-MIB")						# ifDescr, ecc..
load("IP-FORWARD-MIB")				# routing table
load("IP-MIB")						# ipAddress
load("OSPF-MIB")					# ospf
load("MPLS-L3VPN-STD-MIB")			# vrf
load("MPLS-LDP-STD-MIB")			# ldp
load("BGP4-MIB")					# bgp
load("ISIS-MIB")					# isis

load("RFC1213-MIB")					# tcp sessions

try:
	load("CISCO-CDP-MIB")			# cdp
except:
	print "smilint -s -l1 CISCO-CDP-MIB"
예제 #13
0
파일: keepalived.py 프로젝트: wujcheng/lvsm
    def enable(self, protocol, rhost, rport='', vhost='', vport=''):
        """
        Enable a real server in keepalived. This command rellies on snimpy
        and will set the weight of the real server back to its original weight. 
        Assumption: original weight is stored in self.cache_dir/realServerWeight.x.y
        The reason is not used in this case.
        """

        hostips = utils.gethostbyname_ex(rhost)
        if not hostips:
            logger.error('Real server %s is not valid!' % rhost)
            return False

        # Here we only use the first IP if the host has more than one
        hostip = hostips[0]

        if rport:
            # check that it's a valid port
            portnum = utils.getportnum(rport)
            if portnum == -1:
                logger.error('Port %s is not valid!' % rport)
                return False

        if vhost:
            vipnum = utils.gethostname(vhost)
            if not vipnum:
                logger.error('Virtual host %s not valid!' % vhost)
                return False

        if vport:
            vportnum = utils.getportnum(vport)
            if vportnum == -1:
                logger.error('Virtual port %s is not valid!' % vport)
                return False

        try:
            manager.load(self.mib)
            m = manager.Manager(self.snmp_host, self.snmp_community)
            # Not compatible with earlier
            # versions of snimpy
            # secname=self.snmp_user,
            # authpassword=self.snmp_password)
        except (snmp.SNMPException, mib.SMIException) as e:
            logger.error(e)
            logger.error("Unable to perfrom action!")
            return False

        # iterate through the virtual servers
        # and enable the matching real server
        # if the weight is zero.
        # Note: if file is not found in the cache_dir (i.e. /var/cache/lvsm)
        # we set the weight 1 (keepalived default)
        try:
            for i in m.virtualServerAddress:
                hexip = m.virtualServerAddress[i]
                vip = socket.inet_ntoa(hexip)
                logger.debug("Keepalived.enable(): Checking VIP: %s" % vip)
                logger.debug("Keepalived.enable(): Protocol: %s" %
                             str(m.virtualServerProtocol[i]))
                if m.virtualServerProtocol[i] == protocol:
                    if not vhost or vipnum == vip:
                        vp = m.virtualServerPort[i]
                        if not vport or vportnum == vp:
                            # iterate over the realservers in
                            # the specific virtual host
                            j = m.virtualServerRealServersTotal[i]
                            idx = 1
                            while idx <= j:
                                hexip = m.realServerAddress[i, idx]
                                rip = socket.inet_ntoa(hexip)
                                logger.debug("Keepalived.enable(): RIP: %s" %
                                             rip)
                                rp = m.realServerPort[i, idx]
                                if hostip == rip:
                                    if not rport or (rport and portnum == rp):
                                        # Record the original weight somewhere before disabling it
                                        # Will be used when enabling the server
                                        weight = m.realServerWeight[i, idx]
                                        logger.debug(
                                            'Keepalived.enable(): Current weight: %s'
                                            % weight)
                                        if weight > 0:
                                            msg = "Real server %s:%s on VIP %s:%s is already enabled with a weight of %s" % (
                                                rip, rp, vip, vp, weight)
                                            logger.warning(msg)
                                            idx += 1
                                            continue

                                        filename = "realServerWeight.%s.%s" % (
                                            i, idx)
                                        fullpath = '%s/%s' % (self.cache_dir,
                                                              filename)

                                        logger.debug(
                                            'Keepalived.enable(): Enabling %s:%s on VIP %s:%s'
                                            % (rip, rp, vip, vp))
                                        try:
                                            logger.debug(
                                                'Keepalived.enable(): Reading server weight from file: %s'
                                                % fullpath)
                                            f = open(fullpath, 'r')
                                            str_weight = f.readline().rstrip()
                                            f.close()
                                            # make sure the weight is a valid int
                                            orig_weight = int(str_weight)
                                        except IOError as e:
                                            logger.warning(
                                                "%s. Using 1 as default weight!"
                                                % e)
                                            logger.warning(
                                                "To ensure the correct wieght is set, please restart Keepalived."
                                            )
                                            orig_weight = 1

                                        # set the weight to zero
                                        community = "private"
                                        cmd_example = "snmpset -v2c -c %s localhost KEEPALIVED-MIB::%s = %s" % (
                                            community, filename, orig_weight)
                                        logger.info(
                                            "Running equivalent command to: %s"
                                            % cmd_example)
                                        m.realServerWeight[i,
                                                           idx] = orig_weight
                                        print "Enabled %s:%s on VIP %s:%s (%s). Weight set to %s." % (
                                            rip, rp, vip, vp, protocol,
                                            orig_weight)

                                        # Now remove the placeholder file locally
                                        try:
                                            os.unlink(fullpath)
                                        except OSError as e:
                                            logger.error(e)
                                            logger.error(
                                                'Please make sure %s is writable!'
                                                % self.cache_dir)
                                            logger.error(
                                                '%s needs to be manually deleted to avoid future problems.'
                                                % fullpath)

                                        # Try removing the reason file
                                        rfilename = "realServerReason.%s.%s" % (
                                            i, idx)
                                        rfullpath = '%s/%s' % (self.cache_dir,
                                                               rfilename)
                                        try:
                                            os.unlink(rfullpath)
                                        except OSError as e:
                                            logger.error(e)
                                            logger.error(
                                                'Please make sure %s is writable!'
                                                % self.cache_dir)
                                            logger.error(
                                                '%s needs to be manually deleted to avoid future problems.'
                                                % rfullpath)

                                        # remove the placeholder file in other nodes
                                        self.filesync_nodes('remove', fullpath)

                                idx += 1
        except snmp.SNMPException as e:
            logger.error(e)
            logger.error(
                "Unable to complete the command successfully! Please verify manually."
            )
            return False

        return True
예제 #14
0
 def setUpClass(cls):
     load('IF-MIB')
     load('SNMPv2-MIB')
     load(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                       "SNIMPY-MIB.mib"))
     cls.agent = agent.TestAgent()
예제 #15
0
 def setUpClass(cls):
     load('IF-MIB')
     load('SNMPv2-MIB')
     load(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                       "SNIMPY-MIB.mib"))
     cls.agent = agent.TestAgent()
예제 #16
0
def interact(argv=sys.argv):  # pragma: no cover
    conf = Conf().load()

    banner = "\033[1mSnimpy\033[0m ({0}) -- {1}.\n".format(
        snimpy.__version__, snimpy.__doc__)
    banner += "  load        -> load an additional MIB\n"
    banner += "  M           -> manager object"

    local = {
        "conf": conf,
        "M": manager.Manager,
        "load": manager.load,
        "timedelta": timedelta,
        "snmp": manager.snmp
    }

    if len(argv) <= 1:
        manager.Manager._complete = True

    for ms in conf.mibs:
        manager.load(ms)

    globals().update(local)

    if len(argv) > 1:
        argv = argv[1:]
        exec(compile(open(argv[0]).read(), argv[0], 'exec')) in local
        return

    try:
        try:
            try:
                # ipython >= 1.0
                from IPython.terminal.embed import \
                    InteractiveShellEmbed
            except ImportError:
                # ipython >= 0.11
                from IPython.frontend.terminal.embed import \
                    InteractiveShellEmbed
            import IPython
            if IPython.version_info < (4, ):
                from IPython.config.loader import Config
            else:
                from traitlets.config.loader import Config
            cfg = Config()
            try:
                # >= 0.12
                cfg.PromptManager.in_template = "Snimpy [\\#]> "
                cfg.PromptManager.out_template = "Snimpy [\\#]: "
            except ImportError:
                # 0.11
                cfg.InteractiveShellEmbed.prompt_in1 = "Snimpy [\\#]> "
                cfg.InteractiveShellEmbed.prompt_out = "Snimpy [\\#]: "
            if conf.ipythonprofile:
                cfg.InteractiveShellEmbed.profile = conf.ipythonprofile
            shell = InteractiveShellEmbed(config=cfg,
                                          banner1=banner,
                                          user_ns=local)
            # Not interested by traceback in this module
            shell.InteractiveTB.tb_offset += 1
        except ImportError:
            # ipython < 0.11
            from IPython.Shell import IPShellEmbed
            argv = [
                "-prompt_in1", "Snimpy [\\#]> ", "-prompt_out",
                "Snimpy [\\#]: "
            ]
            if conf.ipythonprofile:
                argv += ["-profile", conf.ipythonprofile]
            shell = IPShellEmbed(argv=argv, banner=banner, user_ns=local)
            # Not interested by traceback in this module
            shell.IP.InteractiveTB.tb_offset += 1
    except ImportError:
        shell = None

    if shell and conf.ipython:
        shell()
    else:
        try:
            import rlcompleter
            import readline
        except ImportError:
            readline = None
        if readline:
            if conf.histfile:
                try:
                    readline.read_history_file(
                        os.path.expanduser(conf.histfile))
                except IOError:
                    pass
                atexit.register(lambda: readline.write_history_file(
                    os.path.expanduser(conf.histfile)))

            readline.set_completer(rlcompleter.Completer(local).complete)
            readline.parse_and_bind("tab: menu-complete")
        sys.ps1 = conf.prompt
        code.interact(banner=banner, local=local)
예제 #17
0
import error_handling
import sysoidan
import sshcmd

# Snimpy SNMP lib and MIB loading
from snimpy.manager import Manager as M
from snimpy.manager import load
from snimpy import snmp

mib_path = script_path + '/mibs/'

# RTF FAQ 
os.environ['SMIPATH'] = mib_path

# base MIBs that everyone uses at some point
load(mib_path + "SNMPv2-SMI.my")
load(mib_path + "SNMPv2-TC.my")
load(mib_path + "SNMPv2-CONF.my")
load(mib_path + "SNMP-FRAMEWORK-MIB.my")
load(mib_path + "INET-ADDRESS-MIB.my")
load(mib_path + "RMON-MIB.my")
load(mib_path + "IANAifType-MIB.my")
load(mib_path + "IF-MIB.my")
load(mib_path + "SNMPv2-MIB.my")

# entity, for serial-#
load(mib_path + "ENTITY-MIB.my")

# Cisco stacks
load(mib_path + "CISCO-SMI.my")
load(mib_path + "CISCO-TC.my")
예제 #18
0
파일: apc.py 프로젝트: gwythaint/r4d
# {
#    echo "Rebooting device $1"
#    snmpset -v1 -cprivate $SWITCH_ADDRESS $BASE_SWITCH_OID.$1 i 3 >> /dev/null
# }

import logging
import os

from r4d.db import PowerControl
from snimpy.manager import Manager
from snimpy.manager import load

log = logging.getLogger(__name__)

mibpath = os.path.dirname(__file__)
load(os.path.join(mibpath, "powernet404.mib"))


def register(parent):
    log.debug("register " + __name__)
    parent._add_model('apc', apc)


class apc(PowerControl):
    __mapper_args__ = {'polymorphic_identity': 'apc'}

    def num_ports(self):
        m = Manager(self.URI, "public", 2)
        return m.rPDUOutletDevNumTotalOutlets

    def poweron(self, port):
예제 #19
0
# Copyright Jason Kack – [email protected]
# Using MIT License
# Version 0.5k

import os, sys
from IPy import IP
from netaddr import *
from snimpy.manager import Manager as M, load, snmp

try:
	modem_host = IP(sys.argv[1])
except:
	sys.exit("Invalid argument. Just provide an ip. Thats it")
try:
	# Loading mibs we will need
	load("DOCS-CABLE-DEVICE-MIB")
	load("SNMPv2-MIB")
	load("IF-MIB")
	load("SNMPv2-SMI")
	load("DISMAN-EVENT-MIB")
	load("DOCS-IF-MIB")
	load("RFC1213-MIB")
	load("BRIDGE-MIB")
	load("DOCS-IF31-MIB")
	load("DOCS-PNM-MIB")
	load("DOCS-IF-EXT-MIB")



	modem = str(modem_host)
	host = M(host=modem, community="public", version=2, timeout=1, retries=2)
예제 #20
0
 def load_mib(self, mib):
     flagname = 'SNMP: ' + mib
     if not self.type.has_flag(flagname):
         raise NotImplementedError('Current device does not implement %s' %
                                   (mib, ))
     mgr.load(mib)
def main():

    mib.path(mib.path() + ":/usr/share/mibs/cisco")
    load("SNMPv2-MIB")
    load("IF-MIB")
    load("IP-MIB")
    load("RFC1213-MIB")
    load("CISCO-QUEUE-MIB")
    #Requires MIB RFC-1212 (add to /usr/share/mibs/ietf/)

    parser = argparse.ArgumentParser()
    parser.add_argument('-r',
                        '--router',
                        nargs='?',
                        required=True,
                        help='address of router to monitor')
    parser.add_argument('-s',
                        '--sinterval',
                        type=int,
                        help='sampling interval (seconds)',
                        default=5)
    args = parser.parse_args()
    myInterval = args.sinterval
    print(args)

    #Creates SNMP manager for router with address args.router
    m = M(args.router,
          'private',
          3,
          secname='uDDR',
          authprotocol="MD5",
          authpassword="******",
          privprotocol="AES",
          privpassword="******")

    print(m.sysDescr)  #Gets sysDescr from SNMPv2-MIB

    print("===")

    print(m.ifDescr.items()
          )  #Lists (order, name) interfaces in ifDescr from IF-MIB

    for i, name in m.ifDescr.items():
        print("Interface order %d: %s" % (i, name))

    print("===")

    print(
        m.ipAddressIfIndex.items()
    )  #Lists ((adr.type,adr),order) interfaces in ipAddressIfIndex from IP-MIB

    ifWithAddr = {}
    #Stores (order, first adr.) of all interfaces
    for addr, i in m.ipAddressIfIndex.items():
        if not i in ifWithAddr:
            ifWithAddr.update({i: IPfromOctetString(addr[0], addr[1])})
        print('%s, Interface order: %d, %s' %
              (IPfromOctetString(addr[0], addr[1]), i, m.ifDescr[i]))

    print(ifWithAddr)

    print("===========================================================")
    f = open("InOutPkts.txt", 'w')
    fByte = open("InOutBytes.txt", 'w')
    last_outpackets = [None] * 10
    last_inPkts = [None] * 10
    last_outByte = [0] * 10
    last_inByte = [0] * 10
    for i, name in m.ifHCOutUcastPkts.items():
        last_outpackets[i] = name
    for i, name in m.ifHCInUcastPkts.items():
        last_inPkts[i] = name
    for i, name in m.ifHCOutOctets.items():
        last_outByte[i] = name
    for i, name in m.ifHCInOctets.items():
        last_inByte[i] = name
    listInterfaces = []
    listValues = []
    try:
        while (True):
            listInterfaces = []
            listValues = []
            printFlag = False
            interval = time.time()
            if ((interval - lastTime) >= myInterval):
                global lastTime
                lastTime = time.time()
                printFlag = True
            if (printFlag == True):
                print("		==Out Packets==")
                f.write("Router : %s	==Out Packets==\n" % args.router)
                for i, name in m.ifHCOutUcastPkts.items():
                    print(
                        "Interface %d: Packets send in the last interval: %s" %
                        (i, (name - last_outpackets[i])))
                    f.write(
                        "Interface %d: Packets send in the last interval: %s\n"
                        % (i, (name - last_outpackets[i])))
                    listInterfaces = listInterfaces + [int(i)]
                    listValues = listValues + [int(name - last_outpackets[i])]
                    last_outpackets[i] = name
                plt.plot(listInterfaces, listValues)
                plt.title("Out Packets")
                plt.ylabel("Out Packets")
                plt.xlabel("Interfaces")
                plt.show()
                print("		==In Packets==")
                f.write("Router : %s	==In Packets==\n" % args.router)
                listInterfaces = []
                listValues = []
                for i, name in m.ifHCInUcastPkts.items():
                    print(
                        "Interface %d: Packets receive in the last interval: %s"
                        % (i, (name - last_inPkts[i])))
                    f.write(
                        "Interface %d: Packets receive in the last interval: %s\n"
                        % (i, (name - last_inPkts[i])))
                    listInterfaces = listInterfaces + [int(i)]
                    listValues = listValues + [int(name - last_inPkts[i])]
                    last_inPkts[i] = name
                plt.plot(listInterfaces, listValues)
                plt.title("==In Packets==")
                plt.ylabel("In Packets")
                plt.xlabel("Interfaces")
                plt.show()
                f.write("===============================================\n")
                print("		==Out Bytes==")
                listInterfaces = []
                listValues = []
                fByte.write("Router : %s	==Out Bytes==\n" % args.router)
                for i, name in m.ifHCOutOctets.items():
                    print("Interface %d: Bytes send in the last interval: %s" %
                          (i, (name - last_outByte[i])))
                    fByte.write(
                        "Interface %d: Bytes send in the last interval: %s\n" %
                        (i, (name - last_outByte[i])))
                    listInterfaces = listInterfaces + [int(i)]
                    listValues = listValues + [int(name - last_outByte[i])]
                    last_outByte[i] = name
                plt.plot(listInterfaces, listValues)
                plt.title("==Out Bytes==")
                plt.ylabel("Out Bytes")
                plt.xlabel("Interfaces")
                plt.show()
                print("		==In Bytes==")
                listInterfaces = []
                listValues = []
                fByte.write("Router : %s	==In Bytes==\n" % args.router)
                for i, name in m.ifHCInOctets.items():
                    print(
                        "Interface %d: Bytes receive in the last interval: %s"
                        % (i, (name - last_inByte[i])))
                    fByte.write(
                        "Interface %d: Bytes receive in the last interval: %s\n"
                        % (i, (name - last_inByte[i])))
                    listInterfaces = listInterfaces + [int(i)]
                    listValues = listValues + [int(name - last_inByte[i])]
                    last_inByte[i] = name
                plt.plot(listInterfaces, listValues)
                plt.title("==In Bytes==")
                plt.ylabel("In Bytes")
                plt.xlabel("Interfaces")
                plt.show()
                fByte.write(
                    "===============================================\n")
    except KeyboardInterrupt:
        f.close()
        exit
예제 #22
0
# http://www.oidview.com/mibs/9/CISCO-PROCESS-MIB.html
# https://supportforums.cisco.com/document/30366/oids-management
#
# + place where place mibs on mac
# cd /usr/local/share/mibs/ietf
# cd /usr/local/Cellar/libsmi/0.4.8/share/mibs/ietf

# buitins
import logging

# pip install

from snimpy.manager import Manager as M
from snimpy.manager import load

load("RFC1213-MIB")					# sysName, ecc..
load("IP-FORWARD-MIB")
load("IF-MIB")
load("SNMPv2-MIB")
load("SNMPv2-SMI")
load("CISCO-PROCESS-MIB")
load("CISCO-MEMORY-POOL-MIB")

class Device(object):

	snmpCommunity = "public"
	snmpTarget = ""
	sysName = ""
	sysDescr = ""
	sysObjectID = ""
예제 #23
0
파일: keepalived.py 프로젝트: khosrow/lvsm
    def enable(self, protocol, rhost, rport='',vhost='', vport=''):
        """
        Enable a real server in keepalived. This command rellies on snimpy
        and will set the weight of the real server back to its original weight. 
        Assumption: original weight is stored in self.cache_dir/realServerWeight.x.y
        The reason is not used in this case.
        """

        hostips = utils.gethostbyname_ex(rhost)
        if not hostips:
            logger.error('Real server %s is not valid!' % rhost)
            return False

        # Here we only use the first IP if the host has more than one
        hostip = hostips[0]

        if rport:
            # check that it's a valid port
            portnum = utils.getportnum(rport)
            if portnum == -1:
                logger.error('Port %s is not valid!' % rport)
                return False
        
        if vhost:
            vipnum = utils.gethostname(vhost)
            if not vipnum:
                logger.error('Virtual host %s not valid!' % vhost)
                return False

        if vport:
            vportnum = utils.getportnum(vport)
            if vportnum == -1:
                logger.error('Virtual port %s is not valid!' % vport)
                return False
        
        try:
            manager.load(self.mib)
            m = manager.Manager(self.snmp_host, self.snmp_community)
                                # Not compatible with earlier 
                                # versions of snimpy
                                # secname=self.snmp_user,
                                # authpassword=self.snmp_password)
        except (snmp.SNMPException, mib.SMIException) as e:
            logger.error(e)
            logger.error("Unable to perfrom action!")
            return False

        # iterate through the virtual servers
        # and enable the matching real server
        # if the weight is zero.
        # Note: if file is not found in the cache_dir (i.e. /var/cache/lvsm)
        # we set the weight 1 (keepalived default)
        try:
            for i in m.virtualServerAddress:
                hexip = m.virtualServerAddress[i]
                vip = socket.inet_ntoa(hexip)
                logger.debug("Keepalived.enable(): Checking VIP: %s" % vip)
                logger.debug("Keepalived.enable(): Protocol: %s" % str(m.virtualServerProtocol[i]))
                if m.virtualServerProtocol[i] == protocol:
                    if not vhost or vipnum == vip:
                        vp = m.virtualServerPort[i]
                        if not vport or vportnum == vp:
                            # iterate over the realservers in 
                            # the specific virtual host
                            j = m.virtualServerRealServersTotal[i]
                            idx = 1
                            while idx <= j:
                                hexip = m.realServerAddress[i,idx]
                                rip = socket.inet_ntoa(hexip)
                                logger.debug("Keepalived.enable(): RIP: %s" % rip)
                                rp = m.realServerPort[i,idx]
                                if hostip == rip:
                                    if not rport or (rport and portnum == rp):
                                        # Record the original weight somewhere before disabling it
                                        # Will be used when enabling the server
                                        weight = m.realServerWeight[i,idx]
                                        logger.debug('Keepalived.enable(): Current weight: %s' % weight)
                                        if weight > 0:
                                            msg = "Real server %s:%s on VIP %s:%s is already enabled with a weight of %s" % (rip, rp, vip, vp, weight)
                                            logger.warning(msg)
                                            idx += 1 
                                            continue

                                        filename = "realServerWeight.%s.%s" % (i, idx)
                                        fullpath = '%s/%s' % (self.cache_dir, filename)

                                        logger.debug('Keepalived.enable(): Enabling %s:%s on VIP %s:%s' % (rip, rp, vip, vp))
                                        try:
                                            logger.debug('Keepalived.enable(): Reading server weight from file: %s' % fullpath)
                                            f = open(fullpath, 'r')
                                            str_weight = f.readline().rstrip()
                                            f.close()
                                            # make sure the weight is a valid int 
                                            orig_weight = int(str_weight) 
                                        except IOError as e:
                                            logger.warning("%s. Using 1 as default weight!" % e)
                                            logger.warning("To ensure the correct wieght is set, please restart Keepalived.")
                                            orig_weight = 1
                                       
                                        # set the weight to zero
                                        community = "private"
                                        cmd_example = "snmpset -v2c -c %s localhost KEEPALIVED-MIB::%s = %s" % (community, filename, orig_weight)
                                        logger.info("Running equivalent command to: %s" % cmd_example)
                                        m.realServerWeight[i,idx] = orig_weight
                                        print "Enabled %s:%s on VIP %s:%s (%s). Weight set to %s." % (rip, rp, vip, vp, protocol, orig_weight)

                                        # Now remove the placeholder file locally
                                        try:
                                            logger.debug("Keeplived.enable(): removing placehodler file")
                                            os.unlink(fullpath)
                                        except OSError as e:
                                            logger.error(e)
                                            logger.error('Please make sure %s is writable!' % self.cache_dir)
                                            logger.error('%s needs to be manually deleted to avoid future problems.' % fullpath)

                                        # Try removing the reason file
                                        rfilename = "realServerReason.%s.%s" % (i, idx)
                                        rfullpath = '%s/%s' % (self.cache_dir, rfilename)
                                        try:
                                            logger.debug("Keeplived.enable(): removing reason file")
                                            os.unlink(rfullpath)
                                        except OSError as e:
                                            logger.error(e)
                                            logger.error('Please make sure %s is writable!' % self.cache_dir)
                                            logger.error('%s needs to be manually deleted to avoid future problems.' % rfullpath)


                                        # remove the placeholder file in other nodes
                                        self.filesync_nodes('remove', fullpath)

                                idx += 1
        except snmp.SNMPException as e:
            logger.error(e)
            logger.error("Unable to complete the command successfully! Please verify manually.")
            return False 

        return True
예제 #24
0
def main():
    mib.path(mib.path() + ":/usr/share/mibs/cisco")
    load("SNMPv2-MIB")
    load("IF-MIB")
    load("IP-MIB")
    load("RFC1213-MIB")
    load("CISCO-QUEUE-MIB")
    # Requires MIB RFC-1212 (add to /usr/share/mibs/ietf/)

    parser = argparse.ArgumentParser()
    parser.add_argument('-r', '--router', nargs='?', required=True, help='address of router to monitor')
    parser.add_argument('-s', '--sinterval', type=int, help='sampling interval (seconds)', default=5)
    args = parser.parse_args()

    sys.stdout = Logger("router_" + args.router)

    print(args)

    # Creates SNMP manager for router with address args.router
    m = M(args.router, 'private', 3, secname='uDDR', authprotocol="MD5", authpassword="******", privprotocol="AES",
          privpassword="******")

    print(m.sysDescr)  # Gets sysDescr from SNMPv2-MIB

    print("##################")

    # print(m.ifDescr.items()) #Lists (order, name) interfaces in ifDescr from IF-MIB

    for i, name in m.ifDescr.items():
        print("Interface order %d: %s" % (i, name))

    print("##################")

    ifWithAddr = {}  # Stores the interfaces with IP address
    for addr, i in m.ipAddressIfIndex.items():
        if i not in ifWithAddr:
            ifWithAddr.update({i: {"ip": ip_from_octet_string(addr[0], addr[1]), "name": m.ifDescr[i]}})
        print('%s, Interface order: %d, %s' % (ip_from_octet_string(addr[0], addr[1]), i, m.ifDescr[i]))

    t = 0

    ifOutUCastPkts = {}
    ifInUCastPkts = {}
    ifOutOctets = {}
    ifInOctets = {}
    ifQstats = {}

    """
    ## load from json
    with open('router_10.0.0.2.json') as data_file:
        content = json.load(data_file)

    ifOutUCastPkts = content["ifOutUCastPkts"]
    ifInUCastPkts = content["ifInUCastPkts"]
    ifOutOctets = content["ifOutUCastPkts"]
    ifInOctets = content["ifOutUCastPkts"]
    ifQstats = content["ifOutUCastPkts"]

    draw_plt(ifWithAddr, ifOutUCastPkts, ifInUCastPkts, ifOutOctets, ifInOctets, ifQstats)
    exit()
    """

    try:
        prevOutUCastPkts = {}
        prevInUCastPkts = {}
        prevOutOctets = {}
        prevInOctets = {}
        previfQstats = {}

        for i in ifWithAddr.keys():
            prevOutUCastPkts[i] = 0
            prevInUCastPkts[i] = 0
            prevOutOctets[i] = 0
            prevInOctets[i] = 0
            previfQstats[i] = 0

        count = 0

        while True:
            print("\n=== %d Seconds passed ===" % t)

            """
            # ifHCOutUcastPkts
            The total number of packets that higher-level protocols
            requested be transmitted, and which were not addressed to a
            multicast or broadcast address at this sub-layer, including
            those that were discarded or not sent. This object is a
            64-bit version of ifOutUcastPkts.

            Discontinuities in the value of this counter can occur at
            re-initialization of the management system, and at other
            times as indicated by the value of
            ifCounterDiscontinuityTime."
            """
            print("\n### ifOutUCastPkts")
            ifOutUCastPkts[t] = {}

            for i, pkts in m.ifHCOutUcastPkts.items():
                if i in ifWithAddr.keys():
                    if i not in ifOutUCastPkts[t]:
                        if count == 0:
                            ifOutUCastPkts[t].update({i: 0})
                        else:
                            ifOutUCastPkts[t].update({i: pkts - prevOutUCastPkts[i]})

                        prevOutUCastPkts[i] = pkts

                    print('%s, Interface Out packets: %d' % (m.ifDescr[i], ifOutUCastPkts[t][i]))

            """
            The number of packets, delivered by this sub-layer to a
            higher (sub-)layer, which were not addressed to a multicast
            or broadcast address at this sub-layer. This object is a
            64-bit version of ifInUcastPkts.

            Discontinuities in the value of this counter can occur at
            re-initialization of the management system, and at other
            times as indicated by the value of
            ifCounterDiscontinuityTime.
            """
            print("\n### ifInUCastPkts")
            ifInUCastPkts[t] = {}

            for i, pkts in m.ifHCInUcastPkts.items():
                if i in ifWithAddr.keys():
                    if i not in ifInUCastPkts[t]:
                        if count == 0:
                            ifInUCastPkts[t].update({i: 0})
                        else:
                            ifInUCastPkts[t].update({i: pkts - prevInUCastPkts[i]})

                        prevInUCastPkts[i] = pkts
                    print('%s, Interface In packets: %d' % (m.ifDescr[i], ifInUCastPkts[t][i]))

            """
            The total number of octets transmitted out of the
            interface, including framing characters. This object is a
            64-bit version of ifOutOctets.

            Discontinuities in the value of this counter can occur at
            re-initialization of the management system, and at other
            times as indicated by the value of
            ifCounterDiscontinuityTime.
            """
            print("\n### ifOutOctets")
            ifOutOctets[t] = {}

            for i, pkts in m.ifHCOutOctets.items():
                if i in ifWithAddr.keys():
                    if i not in ifOutOctets[t]:
                        if count == 0:
                            ifOutOctets[t].update({i: 0})
                        else:
                            ifOutOctets[t].update({i: pkts - prevOutOctets[i]})

                        prevOutOctets[i] = pkts
                    print('%s, Interface Out octets: %d' % (m.ifDescr[i], ifOutOctets[t][i]))

            """
            The total number of octets received on the interface,
            including framing characters. This object is a 64-bit
            version of ifInOctets.

            Discontinuities in the value of this counter can occur at
            re-initialization of the management system, and at other
            times as indicated by the value of
            ifCounterDiscontinuityTime.
            """
            print("\n### ifInOctets")
            ifInOctets[t] = {}

            for i, pkts in m.ifHCInOctets.items():
                if i in ifWithAddr.keys():
                    if i not in ifInOctets[t]:
                        if count == 0:
                            ifInOctets[t].update({i: 0})
                        else:
                            ifInOctets[t].update({i: pkts - prevInOctets[i]})

                        prevInOctets[i] = pkts
                    print('%s, Interface In octets: %d' % (m.ifDescr[i], ifInOctets[t][i]))

            """
            The number of messages in the sub-queue.
            """
            print("\n### ifQstats")
            ifQstats[t] = {}

            for (i, u), pkts in m.cQStatsDepth.items():
                if i in ifWithAddr.keys():
                    if i not in ifQstats[t]:
                        if count == 0:
                            ifQstats[t].update({i: 0})
                        else:
                            ifQstats[t].update({i: pkts - previfQstats[i]})
                        previfQstats[i] = pkts
                    print('%s, Interface Queue Size: %d' % (m.ifDescr[i], ifQstats[t][i]))

            plt.ion()

            timeList = []

            for t, value in ifOutUCastPkts.items():
                timeList.append(int(t))
            timeList = sorted(timeList, key=int)

            for i, details in ifWithAddr.items():
                fig = plt.figure(i, figsize=(16, 10), dpi=80)
                fig.canvas.set_window_title(str(details["name"]) + ' ' + str(details["ip"]))
                fig.subplots_adjust(wspace=0.23)

                # ifOutUCastPkts
                xitems = timeList
                yitems = []

                for t in timeList:
                    yitems.append(ifOutUCastPkts[t][i])

                plt.subplot(231)
                plt.plot(xitems, yitems)
                plt.title("Interface out")
                plt.xlabel("time (s)")
                plt.ylabel("Unicast packets")
                plt.grid(True)

                # ifInUCastPkts
                xitems = timeList
                yitems = []

                for t in timeList:
                    yitems.append(ifInUCastPkts[t][i])

                plt.subplot(232)
                plt.plot(xitems, yitems)
                plt.title("Interface in")
                plt.ylabel("Unicast packets")
                plt.xlabel("time (s)")
                plt.grid(True)

                # ifOutOctets
                xitems = timeList
                yitems = []

                for t in timeList:
                    yitems.append(ifOutOctets[t][i])

                plt.subplot(233)
                plt.plot(xitems, yitems)
                plt.title("Number of bytes transmitted")
                plt.ylabel("Number of bytes")
                plt.xlabel("time (s)")
                plt.grid(True)

                # ifInOctets
                xitems = timeList
                yitems = []

                for t in timeList:
                    yitems.append(ifInOctets[t][i])

                plt.subplot(234)
                plt.plot(xitems, yitems)
                plt.title("Number of bytes received")
                plt.ylabel("Number of bytes")
                plt.xlabel("time (s)")
                plt.grid(True)
                plt.draw()

                # ifQstats
                xitems = timeList
                yitems = []

                for t in timeList:
                    yitems.append(ifQstats[t][i])

                plt.subplot(235)
                plt.plot(xitems, yitems)
                plt.title("The number of messages in the sub-queue.")
                plt.ylabel("Number of messages")
                plt.xlabel("time (s)")
                plt.grid(True)
                plt.draw()
            time.sleep(args.sinterval)
            t += args.sinterval
            count += 1

    except KeyboardInterrupt:
        print "Finished after %d seconds..." % t
        json_save(args, ifWithAddr, ifOutUCastPkts, ifInUCastPkts, ifOutOctets, ifInOctets, ifQstats)
예제 #25
0
파일: keepalived.py 프로젝트: khosrow/lvsm
    def disable(self, protocol, host, port='', vhost='', vport='', reason=''):
        """
        Disable a real server in keepalived. This command rellies on snimpy
        and will set the weight of the real server to 0.
        The reason is not used in this case.
        """
        found = False

        hostips = utils.gethostbyname_ex(host)
        if not hostips:
            logger.error('Real server %s is not valid!' % host)
            return False

        # Here we only use the first IP if the host has more than one
        hostip = hostips[0]
        if port:
            # check that it's a valid port
            portnum = utils.getportnum(port)
            if portnum == -1:
                logger.error('Port %s is not valid!' % port)
                return False
        
        if vhost:
            vipnums = utils.gethostbyname_ex(vhost)
            if not vipnums:
                logger.error('Virtual host %s not valid!' % vhost)
                return False

            # only take the first ip address if host has more than one
            vipnum = vipnums[0]

        if vport:
            vportnum = utils.getportnum(vport)
            if vportnum == -1:
                logger.error('Virtual port %s is not valid!' % vport)
                return False
        
        try:
            manager.load(self.mib)
            m = manager.Manager(self.snmp_host, self.snmp_community)
                                # Not compatible with earlier 
                                # versions of snimpy
                                #secname=self.snmp_user,
                                #authpassword=self.snmp_password)
        except (snmp.SNMPException, mib.SMIException) as e:
            logger.error(e)
            logger.error("Unable to perfrom action!")
            return False

        # iterate through the virtual servers
        # and disable the matching real server
        try:
            for i in m.virtualServerAddress:
                hexip = m.virtualServerAddress[i]
                vip = socket.inet_ntoa(hexip)
                logger.debug("Keepalived.disable(): Checking VIP: %s" % vip)
                logger.debug("Keepalived.disable(): Protocol: %s" % str(m.virtualServerProtocol[i]))
                if m.virtualServerProtocol[i] == protocol:
                    if not vhost or vipnum == vip:
                        vp = m.virtualServerPort[i]
                        if not vport or vportnum == vp:
                            # iterate over the realservers in 
                            # the specific virtual
                            j = m.virtualServerRealServersTotal[i]
                            idx = 1                    
                            while idx <= j:
                                hexip = m.realServerAddress[i,idx]
                                rip = socket.inet_ntoa(hexip)
                                rp = m.realServerPort[i,idx]
                                if hostip == rip:                                                        
                                    if not port or (port and portnum == rp):
                                        logger.debug('Keepalived.disable(): Disabling %s:%s on VIP %s:%s' % (rip, rp, vip, vp))
                                        # 'found' is used to keep track of
                                        # matching real servers to disable
                                        found = True

                                        # Record the original weight
                                        # before disabling it
                                        # It'll be used when enabling 
                                        weight = m.realServerWeight[i,idx]
                                        logger.debug('Keepalived.disable(): Current weight: %s' % weight)

                                        if weight == 0:
                                            logger.warning("Real server %s:%s is already disabled on VIP %s:%s" % (rip, rp, vip, vp))
                                            idx += 1
                                            continue

                                        filename = "realServerWeight.%s.%s" % (i, idx)
                                        fullpath = '%s/%s' % (self.cache_dir, filename)
                                        rfilename = "realServerReason.%s.%s" % (i, idx)
                                        rfullpath = '%s/%s' % (self.cache_dir, rfilename)
                                        try:
                                            # Create a file with the original weight 
                                            logger.info('Creating file: %s' % fullpath)
                                            f = open(fullpath, 'w')
                                            f.write(str(weight))
                                            f.close()

                                            # Create a file with the disable reason
                                            logger.info('Creating file: %s' % rfullpath)
                                            f = open(rfullpath, 'w')
                                            f.write(str(reason))
                                            f.close()
                                        except IOError as e:
                                            logger.error(e)
                                            logger.error('Please make sure %s is writable before proceeding!' % self.cache_dir)
                                            return False 

                                        # Copy the file to the other nodes
                                        # In case of a switch lvsm will have 
                                        # the weight info on all nodes
                                        self.filesync_nodes('copy', fullpath)
                            
                                        # set the weight to zero
                                        community = "private"
                                        cmd_example = "snmpset -v2c -c %s localhost KEEPALIVED-MIB::%s = 0" % (community, filename)
                                        logger.info("Running equivalent command to: %s" % cmd_example)
                                        m.realServerWeight[i,idx] = 0
                                        print "Disabled %s:%s on VIP %s:%s (%s). Weight set to 0." % (rip, rp, vip, vp, protocol)
                                idx += 1
        except snmp.SNMPException as e:
            logger.error(e)
            logger.error("Unable to complete the command successfully! Please verify manually.")
            return False 

        if not found:
            logger.error('No matching real servers were found!')
            return False
        else:
            return True
예제 #26
0
#!/usr/bin/python
import sys
from snimpy.manager import Manager as M
from snimpy.manager import load
import time

#Orden de carga correcto
load("mibs/RFC1155-SMI.mib")
load("mibs/RFC-1212.mib")
load("mibs/rfc1213.mib")
load("./SNMPv2-SMI.my")
load("./SNMPv2-TC.my")
load("./SNMPv2-CONF.my")
load("mibs/rfc2819.mib")#MIB de RMON
#########################
ip="192.168.0.197:8001"
m = M(ip, community="public", version=2)
topspeed=10 #MegaBits por segundo
def calculaUtilizacion(oldcounter,newcounter,interval,topspeed):
	#Ancho de banda empleado en bytes por segundo
	usedspeed=(newcounter-oldcounter)/interval
	#
	utilizacion= (usedspeed*8)/(topspeed*1e6);
	return utilizacion

#def barraLed(utilizacion)
	
#oldcounter=0

#while True:
	#tiempo=m.sysUpTime
예제 #27
0
# Optionally, let helper handle command-line arguments for us for example --threshold
# Note: If your plugin needs any commandline arguments on its own (like --hostname) you should add them
# before this step with helper.parser.add_option()

helper.parser.add_option("-H", help="Hostname or IP", dest="host", default='localhost')
helper.parser.add_option("--Version", help="Snmp Version", dest="version", default='2')
helper.parser.add_option("-c", help="Snmp Comunity", dest="community", default='public')

helper.parse_arguments()
mib='/usr/share/mibs/site/NetSure-SCU-Plus'

# Here starts our plugin specific logic. Lets try to read /proc/loadavg
# And if it fails, we exit immediately with UNKNOWN status
try:
    load(mib)
except Exception, e:
    helper.exit(summary="Could not read MIB file.", long_output=str(e), exit_code=unknown, perfdata='')

m=Manager(helper.options.host,helper.options.community,int(helper.options.version))

values={'systemCurrent':'','systemUsedCapacity':'','psBatteryVoltage':'','psBatteryCurrent':'','psInputLineAVoltage':''}

formatstring='systemUsedCapacity: %s'
content=m.systemUsedCapacity
helper.add_summary(formatstring % content)

for key in values:
    commandstring="m."+key
    values[key]=eval(commandstring)
#    print key,values[key]
예제 #28
0
def main():
    logging.info('***************************************************************************')
    logging.info('Starting Script')
    deviceCount = 0

    #Prepare exclusions file
    touch(docroot + 'brocade_exclusions')

    #Load required MIBs
    load(docroot + 'mibs/SNMPv2-MIB')
    load(docroot + 'mibs/RFC1155-SMI.txt')
    load(docroot + 'mibs/BRCD_REG.mib')
    load(docroot + 'mibs/BRCD_TC.mib')
    load(docroot + 'mibs/FA.mib')
    load(docroot + 'mibs/FCMGMT-MIB.mib')
    load(docroot + 'mibs/SW.mib')
    load(docroot + 'mibs/HA.mib')

    #Check PagerDuty for open incidents
    try:
        getCurrentAlarms()
    except Exception as inst:
        msg = 'Exception occurred while querying PagerDuty for open incidents; Exception = "{0}"'.format(inst)
        logging.warning('PAGER\tERROR\r{0}'.format(msg))

    script_start = time.time()
    try:
        deviceFile = open(docroot+'brocade_devices','r')
        comm = "public"
        ver = 2
        for line in deviceFile:
            if line[0:1] != "#":
                deviceCount += 1
                start = time.time()
                hostname = line[:-1]
                queryDevice(hostname,comm,ver)
                end = time.time()
                print '{0} - {1} - {2} sec. {3} total sec.'.format(deviceCount,hostname,(end-start),(end-script_start))
    except Exception as inst:
        msg = 'Exception occurred in main function. Exception = "{0}"'.format(inst)
        logging.warning('MAIN\tERROR\t{0}'.format(msg))

    logging.info('TOTAL\tSTATS\t(Checked,OK,Error) || Sensor({1},{2},{3}) || FRU({4},{5},{6}) || Devices({0})'.format(deviceCount,*totalStats))
    logging.info('Script Complete')
예제 #29
0
파일: keepalived.py 프로젝트: wujcheng/lvsm
    def disable(self, protocol, host, port='', vhost='', vport='', reason=''):
        """
        Disable a real server in keepalived. This command rellies on snimpy
        and will set the weight of the real server to 0.
        The reason is not used in this case.
        """
        found = False

        hostips = utils.gethostbyname_ex(host)
        if not hostips:
            logger.error('Real server %s is not valid!' % host)
            return False

        # Here we only use the first IP if the host has more than one
        hostip = hostips[0]
        if port:
            # check that it's a valid port
            portnum = utils.getportnum(port)
            if portnum == -1:
                logger.error('Port %s is not valid!' % port)
                return False

        if vhost:
            vipnums = utils.gethostbyname_ex(vhost)
            if not vipnums:
                logger.error('Virtual host %s not valid!' % vhost)
                return False

            # only take the first ip address if host has more than one
            vipnum = vipnums[0]

        if vport:
            vportnum = utils.getportnum(vport)
            if vportnum == -1:
                logger.error('Virtual port %s is not valid!' % vport)
                return False

        try:
            manager.load(self.mib)
            m = manager.Manager(self.snmp_host, self.snmp_community)
            # Not compatible with earlier
            # versions of snimpy
            #secname=self.snmp_user,
            #authpassword=self.snmp_password)
        except (snmp.SNMPException, mib.SMIException) as e:
            logger.error(e)
            logger.error("Unable to perfrom action!")
            return False

        # iterate through the virtual servers
        # and disable the matching real server
        try:
            for i in m.virtualServerAddress:
                hexip = m.virtualServerAddress[i]
                vip = socket.inet_ntoa(hexip)
                logger.debug("Keepalived.disable(): Checking VIP: %s" % vip)
                logger.debug("Keepalived.disable(): Protocol: %s" %
                             str(m.virtualServerProtocol[i]))
                if m.virtualServerProtocol[i] == protocol:
                    if not vhost or vipnum == vip:
                        vp = m.virtualServerPort[i]
                        if not vport or vportnum == vp:
                            # iterate over the realservers in
                            # the specific virtual
                            j = m.virtualServerRealServersTotal[i]
                            idx = 1
                            while idx <= j:
                                hexip = m.realServerAddress[i, idx]
                                rip = socket.inet_ntoa(hexip)
                                rp = m.realServerPort[i, idx]
                                if hostip == rip:
                                    if not port or (port and portnum == rp):
                                        logger.debug(
                                            'Keepalived.disable(): Disabling %s:%s on VIP %s:%s'
                                            % (rip, rp, vip, vp))
                                        # 'found' is used to keep track of
                                        # matching real servers to disable
                                        found = True

                                        # Record the original weight
                                        # before disabling it
                                        # It'll be used when enabling
                                        weight = m.realServerWeight[i, idx]
                                        logger.debug(
                                            'Keepalived.disable(): Current weight: %s'
                                            % weight)

                                        if weight == 0:
                                            logger.warning(
                                                "Real server %s:%s is already disabled on VIP %s:%s"
                                                % (rip, rp, vip, vp))
                                            idx += 1
                                            continue

                                        filename = "realServerWeight.%s.%s" % (
                                            i, idx)
                                        fullpath = '%s/%s' % (self.cache_dir,
                                                              filename)
                                        rfilename = "realServerReason.%s.%s" % (
                                            i, idx)
                                        rfullpath = '%s/%s' % (self.cache_dir,
                                                               rfilename)
                                        try:
                                            # Create a file with the original weight
                                            logger.info('Creating file: %s' %
                                                        fullpath)
                                            f = open(fullpath, 'w')
                                            f.write(str(weight))
                                            f.close()

                                            # Create a file with the disable reason
                                            logger.info('Creating file: %s' %
                                                        rfullpath)
                                            f = open(rfullpath, 'w')
                                            f.write(str(reason))
                                            f.close()
                                        except IOError as e:
                                            logger.error(e)
                                            logger.error(
                                                'Please make sure %s is writable before proceeding!'
                                                % self.cache_dir)
                                            return False

                                        # Copy the file to the other nodes
                                        # In case of a switch lvsm will have
                                        # the weight info on all nodes
                                        self.filesync_nodes('copy', fullpath)

                                        # set the weight to zero
                                        community = "private"
                                        cmd_example = "snmpset -v2c -c %s localhost KEEPALIVED-MIB::%s = 0" % (
                                            community, filename)
                                        logger.info(
                                            "Running equivalent command to: %s"
                                            % cmd_example)
                                        m.realServerWeight[i, idx] = 0
                                        print "Disabled %s:%s on VIP %s:%s (%s). Weight set to 0." % (
                                            rip, rp, vip, vp, protocol)
                                idx += 1
        except snmp.SNMPException as e:
            logger.error(e)
            logger.error(
                "Unable to complete the command successfully! Please verify manually."
            )
            return False

        if not found:
            logger.error('No matching real servers were found!')
            return False
        else:
            return True
예제 #30
0
    def handle(self, *args, **options):
        log = logging.getLogger('ixpmgr.script')

        conf = util.load_config()

        if options['force']:
            qs = ViewInterface.objects.all()
        else:
            # query for any interface that's enabled for ip and missing hostname
            qs = ViewInterface.objects.filter(~Q(ipv4address=0),
                ipv4enabled=1, ipv4hostname='')
            qs |= ViewInterface.objects.filter(~Q(ipv6address=0),
                ipv6enabled=1, ipv6hostname='')


        qs = Switch.objects.filter(active=True, switchtype=const.SWITCHTYPE_SWITCH)
        for switch in qs:
            print switch.name, switch.hostname, switch.snmppasswd

        print switch.name, switch.hostname, switch.snmppasswd
        cmdGen = cmdgen.CommandGenerator()

        errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
            cmdgen.CommunityData(switch.snmppasswd),
            cmdgen.UdpTransportTarget((switch.hostname, 161)),
            cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0)
        )

        # Check for errors and print out results
        if errorIndication:
            print(errorIndication)
        else:
            if errorStatus:
                print('%s at %s' % (
                    errorStatus.prettyPrint(),
                    errorIndex and varBinds[int(errorIndex)-1] or '?'
                    )
                )
            else:
                for name, val in varBinds:
                    print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))




        load("IF-MIB")
        load("SNMPv2-MIB")
        load("BRIDGE-MIB")
        load("Q-BRIDGE-MIB")
#for id in s.dot1qPortIngressFiltering:

        m = M(switch.hostname, switch.snmppasswd)
        #m = M(switch.hostname, 'dev_aLFMBMoZ30dNy8NqnHDJJgtRfP3', 2)
        #print m.ifDescr[0]
        #print m.sysContact
        print m.ifDescr
#        for idx in m.ifDescr:
#            print m.ifDescr[idx]
# dot1qTpFdbPort
        for i in m.dot1dBasePortIfIndex:
            ifidx = m.dot1dBasePortIfIndex[i]
            print "dot1d: ", i, m.dot1dBasePortIfIndex[i]
예제 #31
0
def main():
    logging.info('***************************************************************************')
    logging.info('Starting Script')
    deviceCount = 0

    #Prepare stats file
    touch(docroot + 'cisco_snmp_alarms_current')
    touch(docroot + 'cisco_snmp_exclusions')
    os.rename(docroot+'cisco_snmp_alarms_current',docroot+'cisco_snmp_alarms_previous')
    touch(docroot + 'cisco_snmp_alarms_current')

    #Parse previous alarms file and output to log file for debugging
    try:
        logPreviousAlarms()
    except Exception as inst:
        msg = 'Exception occurred while parsing previous alarms file. Exception: {0}'.format(inst)
        logging.warning(msg)

    #Load required MIBs
    load(docroot + "mibs/CISCO-SMI.my")
    load(docroot + "mibs/CISCO-TC.my")
    load(docroot + "mibs/ENTITY-MIB.my")
    load(docroot + "mibs/SNMPv2-MIB")
    load(docroot + "mibs/CISCO-ENVMON-MIB.my")
    load(docroot + "mibs/CISCO-ENTITY-FRU-CONTROL-MIB.mib")
    load(docroot + "mibs/CISCO-ENTITY-SENSOR-MIB.mib")
    load(docroot + "mibs/CISCO-FIREWALL-MIB.my")
    # We are using a modified version of the Tempus MIB
    # because the original has syntax errors and cannot be loaded by snimpy
    load(docroot + "mibs/TEMPUSLXUNISON-MIB-SPOT.txt")

    script_start = time.time()
    try:
        deviceFile = open(docroot+'cisco_devices','r')
        comm = "public"
        ver = 2
        for line in deviceFile:
            if line[0:1] != "#":
                deviceCount += 1
                start = time.time()
                hostname = line[:-1]              
                queryDevice(hostname,comm,ver)
                end = time.time()
                print '{0} - {1} - {2} sec. {3} total sec.'.format(deviceCount,hostname,(end-start),(end-script_start))
    except Exception as inst:
        msg = 'Exception occurred in main function. Exception = "{0}"'.format(inst)
        logging.warning('MAIN\tERROR\t{0}'.format(msg))

    logging.info('TOTAL\tSTATS\tIOS\t(Checked,OK,Error) || Fan({1},{2},{3}) || Temp({4},{5},{6}) || PSU({7},{8},{9}) || Devices({0})'.format(iosCount,*totalStatsIOS))
    logging.info('TOTAL\tSTATS\tNXOS\t(Checked,OK,Error) || Fan({1},{2},{3}) || PSU({4},{5},{6}) || Module({7},{8},{9}) || Sensor({10},{11},{12}) || Devices({0})'.format(nxosCount,*totalStatsNXOS))
    logging.info('TOTAL\tSTATS\tASA\t(Checked,OK,Error) || HW({1},{2},{3}) || Conn({4},{5},{6}) || Devices({0})'.format(asaCount,*totalStatsASA))
    logging.info('TOTAL\tSTATS\tPTP\t(Checked,OK,Error) || PTP({1},{2},{3}) || Devices({0})'.format(ptpCount,*totalStatsPTP))
    logging.info('Script Complete')
예제 #32
0
if (pickled):  # Picked input
    import pickle
    mp = pickle.load(open('switches.pickle', 'r'))
    # only needed
    switches = []
    for switchIp in mp.keys():
        if mp[switchIp]:
            switches.append(mp[switchIp][0])

else:
    import os
    import time
    from snimpy.manager import Manager as M
    from snimpy.manager import load

    load("BRIDGE-MIB")

    def find_switches():
        """ find all the switches in the 10.11.12.xxx range """
        sw = dict(
        )  # key/value = ip/mac of all the switches alive at the time of scan
        print "Scanning 10.11.12.xxx range..."
        for num in range(
                130, 254
        ):  #start from 130 as we don't have switches lower than that
            ip = "10.11.12." + str(num)
            if os.system("ping -c 1 -w2 -t2 " + ip +
                         " > /dev/null 2>&1") == 0:  #host is alive!
                print "%s added to the list" % ip
                sw[ip] = ""
            else:
            unit = "Kbps"
            return {'speed': speed, 'unit': unit}
    if input < 125000000:
            speed = str(round((input / 1250) / 100, 2))
            unit = "Mbps"
            return {'speed': speed, 'unit': unit}
    if input > 125000000:
            speed = str(round((speed / 1250000) / 100, 2))
            unit = "Gbps"
            return {'speed': speed, 'unit': unit}

# Wire Firebase
firebaseConnection = firebase.FirebaseApplication(_FIREBASE_ENDPOINT, None)

# Load SNMP MIB
load("IF-MIB")

# SNMP Manager (our client)
m = M(_WAN_HOST, _WAN_COMMUNITY, _WAN_SNMP_VERSION)

last_ifOutOctets = 0
last_ifInOctets = 0
last_timestamp = time.time()

while True:
    # The first time the script runs, we have no change to send
    if last_ifOutOctets == 0:
        last_ifOutOctets = m.ifOutOctets[_WAN_ADAPTER]
        last_ifInOctets = m.ifInOctets[_WAN_ADAPTER]
        last_timestamp = time.time()
    else:
예제 #34
0
파일: baseSNMP.py 프로젝트: bsilvr/DDR-2016
def main():
    mib.path(mib.path()+":/usr/share/mibs/cisco")
    load("SNMPv2-MIB")
    load("IF-MIB")
    load("IP-MIB")
    load("RFC1213-MIB")
    load("CISCO-QUEUE-MIB")
    #Requires MIB RFC-1212 (add to /usr/share/mibs/ietf/)

    parser = argparse.ArgumentParser()
    parser.add_argument('-r', '--router', nargs='?',required=True, help='address of router to monitor')
    parser.add_argument('-s', '--sinterval', type=int, help='sampling interval (seconds)',default=5)
    args=parser.parse_args()

    sys.stdout = Logger("router_" + args.router)

    #Creates SNMP manager for router with address args.router
    m=M(args.router,'private',3, secname='uDDR',authprotocol="MD5", authpassword="******",privprotocol="AES", privpassword="******")

    print(m.sysDescr)   #Gets sysDescr from SNMPv2-MIB

    ifWithAddr={}   #Stores (order, first adr.) of all interfaces
    for addr, i in m.ipAddressIfIndex.items():
        if not i in ifWithAddr:
            ifWithAddr.update({i:IPfromOctetString(addr[0],addr[1])})
            

    t = 0
    
    fig = plt.figure(num=None, figsize=(10, 7.5), dpi=80)
    plt.subplots_adjust(wspace=0.25)
    plt.subplots_adjust(hspace=0.25)
    plt.ion()
    
    try:
        inPkts = {}
        inPktsDiference = {}
        outPkts = {}  
        outPktsDiference = {}
        inOcts = {}
        inOctsDiference = {}
        outOcts = {}
        outOctsDiference = {}
        colors = {}  
        colormap = ['r.-','y.-','g.-','b.-','m.-']
        counter = 0 
        patches=[]
        for i, name in m.ifDescr.items():
            if i in ifWithAddr:
                inPkts.update({name:[]})
                inPktsDiference.update({name:[]})
                outPkts.update({name:[]})
                outPktsDiference.update({name:[]})
                inOcts.update({name:[]})
                inOctsDiference.update({name:[]})
                outOcts.update({name:[]})
                outOctsDiference.update({name:[]})
                
                colors.update({name:colormap[counter]})
                counter +=1
                if counter >= len(colormap):
                    counter =0

        counter = 0
        while True:
            ifOutUCastPkts={} #Stores (order, OutPkts) of all interfaces
            for i, pkts in m.ifHCOutUcastPkts.items():
                if i in ifWithAddr.keys():
                    if not i in ifOutUCastPkts:
                        ifOutUCastPkts.update({i:pkts})

            ifInUCastPkts={} #Stores (order, InPkts) of all interfaces
            for i, pkts in m.ifHCInUcastPkts.items():
                if i in ifWithAddr.keys():
                    if not i in ifInUCastPkts:
                        ifInUCastPkts.update({i:pkts})

            ifOutOctets={} #Stores (order, OutOctets) of all interfaces
            for i, pkts in m.ifHCOutOctets.items():
                if i in ifWithAddr.keys():
                    if not i in ifOutOctets:
                        ifOutOctets.update({i:pkts})

            ifInOctets={} #Stores (order, InOctets) of all interfaces
            for i, pkts in m.ifHCInOctets.items():
                if i in ifWithAddr.keys():
                    if not i in ifInOctets:
                        ifInOctets.update({i:pkts})

            ifQstats={} #Stores (order, queue_size) of all interfaces
            for (i,u),pkts in m.cQStatsDepth.items():
                if i in ifWithAddr.keys():
                    if not i in ifQstats:
                        ifQstats.update({i:pkts})

            x = np.arange(0, t+args.sinterval, 5)
            
            order = []

            aux = 0

            print("=== %d Seconds passed ===" % t)
            for i, name in m.ifDescr.items():
                if i in ifWithAddr:

                    print("%s, %s \t pkts[in/out][%s/%s] \t octets[in/out][%s/%s] \t queue[%s]" % (ifWithAddr[i], name, ifInUCastPkts[i], ifOutUCastPkts[i], ifInOctets[i], ifOutOctets[i], ifQstats[i]))
                    order.append(name)

                    #Plot in Packets
                    plt.subplot(2, 2, 1)
                    plt.title('In Packets')
                    plt.ylabel('Packets')
                    inPkts[name] += [ifInUCastPkts[i]]
                    inPktsDiference[name] += [ifInUCastPkts[i]]
                    if(counter != 0):
                        if counter==1:
                            inPktsDiference[name][1] = inPkts[name][1]-inPkts[name][0]
                            inPktsDiference[name][0] = 0
                        else:
                            inPktsDiference[name][counter] = inPkts[name][counter]-inPkts[name][counter-1]
                        
                        plt.plot(x, inPktsDiference[name], colors[name])    
                    else:
                        plt.plot(x, 0, colors[name])
                    
                    #Plot out Packets
                    plt.subplot(2, 2, 2)
                    plt.title('Out Packets')
                    outPkts[name] += [ifOutUCastPkts[i]]
                    outPktsDiference[name] += [ifOutUCastPkts[i]]
                    if(counter != 0):
                        if counter==1:
                            outPktsDiference[name][1] = outPkts[name][1]-outPkts[name][0]
                            outPktsDiference[name][0] = 0
                        else:
                            outPktsDiference[name][counter] = outPkts[name][counter]-outPkts[name][counter-1]
                        
                        plt.plot(x, outPktsDiference[name], colors[name])    
                    else:
                        plt.plot(x, 0, colors[name])
                    
                    #Plot in Octets
                    plt.subplot(2, 2, 3)
                    plt.title('In Octets')
                    plt.xlabel('Time (s)')
                    plt.ylabel('Octets')
                    inOcts[name] += [ifInOctets[i]]
                    inOctsDiference[name] += [ifInOctets[i]]
                    if(counter != 0):
                        if counter==1:
                            inOctsDiference[name][1] = inOcts[name][1]-inOcts[name][0]
                            inOctsDiference[name][0] = 0
                        else:
                            inOctsDiference[name][counter] = inOcts[name][counter]-inOcts[name][counter-1]
                        
                        plt.plot(x, inOctsDiference[name], colors[name])    
                    else:
                        plt.plot(x, 0, colors[name])
                    
                    #Plot out Octets
                    plt.subplot(2, 2, 0)
                    plt.title('Out Octets')
                    plt.xlabel('Time (s)')
                    outOcts[name] += [ifOutOctets[i]]
                    outOctsDiference[name] += [ifOutOctets[i]]
                    if(counter != 0):
                        if counter==1:
                            outOctsDiference[name][1] = outOcts[name][1]-outOcts[name][0]
                            outOctsDiference[name][0] = 0
                        else:
                            outOctsDiference[name][counter] = outOcts[name][counter]-outOcts[name][counter-1]
                        
                        plt.plot(x, outOctsDiference[name], colors[name])    
                    else:
                        plt.plot(x, 0, colors[name])
                    
                    aux+=1
                        
            print("========================")
            counter+=1       
            plt.subplot(2, 2, 1)
            plt.legend(order, ncol=4, loc='upper center', bbox_to_anchor=[1.1, 1.3], columnspacing=1.0, labelspacing=0.0,handletextpad=0.0, handlelength=1.5, fancybox=True, shadow=True)

            plt.draw()

            time.sleep(args.sinterval)
            t += args.sinterval
            

    except KeyboardInterrupt:
        print "Finished after %d seconds..." % t
        fig.savefig('output.jpg')
        sys.stdout.close()
# Optionally, let helper handle command-line arguments for us for example --threshold
# Note: If your plugin needs any commandline arguments on its own (like --hostname) you should add them
# before this step with helper.parser.add_option()

helper.parser.add_option("-n", help="Interface name (regex)", dest="name", default='.')
helper.parser.add_option("-H", help="Hostname or IP", dest="host", default='localhost')
helper.parser.add_option("--Version", help="Snmp Version", dest="version", default='2')
helper.parser.add_option("-c", help="Snmp Comunity", dest="community", default='public')

helper.parse_arguments()


# Here starts our plugin specific logic. Lets try to read /proc/loadavg
# And if it fails, we exit immediately with UNKNOWN status
try:
    load('IF-MIB')
except Exception, e:
    helper.exit(summary="Could not read MIB file.", long_output=str(e), exit_code=unknown, perfdata='')

m=Manager(helper.options.host,helper.options.community,int(helper.options.version))
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
p = re.compile(helper.options.name)

values=['ifInOctets','ifOutOctets','ifInErrors','ifOutErrors','ifInUcastPkts','ifOutUcastPkts']

for interfaceKey in m.ifIndex:
    if p.search(str(m.ifDescr[interfaceKey])):
        for valuesKey in values:
            now=time.time()
            commandstr='m.'+valuesKey+"[%s]" % interfaceKey
            labelstr=str(m.ifDescr[interfaceKey])+'-'+valuesKey
예제 #36
0
def load_mib(mib):
    if not mib in manager.loaded:
        manager.load(mib)
예제 #37
0
from mongoengine import *
import datetime
from snimpy.manager import Manager, load
from database import ProcessTableEntry, ProcessTable, UptimeScalar, ProcessCount, VideoTableEntry, VideoTable
import time

load("/home/bruno/.snmp/mibs/videoMgr.mib")
host = "104.131.91.218"
community = "vlavaav"
m = Manager(host, community);

def get_process_table():
    pid_list = []
    owner_list = []
    cpu_list = []
    mem_list = []
    state_list = []

    for idx in m.vmProcessOwner:
        owner_list.append(m.vmProcessOwner[idx])

    for idx in m.vmProcessPID:
        pid_list.append(m.vmProcessPID[idx])

    for idx in m.vmProcessCPU:
        cpu_list.append(m.vmProcessCPU[idx])

    for idx in m.vmProcessMem:
        mem_list.append(m.vmProcessMem[idx])

    for idx in m.vmProcessState:
예제 #38
0
#   but the adjacency not established (Junos bug?)
#
# [email protected]

from snimpy.manager import Manager
from snimpy.manager import load
from snimpy.snmp import SNMPNoSuchObject
import sys
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--host", nargs=1, dest='host', required=True, help="Target hostname")
parser.add_argument("--community", nargs=1, dest='community', required=True, help="SNMP community")
options = parser.parse_args()

load('JUNIPER-VIRTUALCHASSIS-MIB')

snimpyManager = Manager(options.host[0], options.community[0], 2, cache=True)

return_code = 0
return_message = []
up_count = 0
down_count = 0
unknown_count = 0

for index in snimpyManager.jnxVirtualChassisPortAdminStatus:
    adminStatus = snimpyManager.jnxVirtualChassisPortAdminStatus[index]
    operStatus = snimpyManager.jnxVirtualChassisPortOperStatus[index]
    try:
        portName = snimpyManager.jnxVirtualChassisPortName[index]
        fpcId = snimpyManager.jnxVirtualChassisFpcId[index]
예제 #39
0
파일: main.py 프로젝트: AudricP/snimpy
def interact(argv=sys.argv):  # pragma: no cover
    conf = Conf().load()

    banner = "\033[1mSnimpy\033[0m ({0}) -- {1}.\n".format(
        snimpy.__version__, snimpy.__doc__)
    banner += "  load        -> load an additional MIB\n"
    banner += "  M           -> manager object"

    local = {"conf": conf,
             "M": manager.Manager,
             "load": manager.load,
             "timedelta": timedelta,
             "snmp": manager.snmp
             }

    if len(argv) <= 1:
        manager.Manager._complete = True

    for ms in conf.mibs:
        manager.load(ms)

    globals().update(local)

    if len(argv) > 1:
        argv = argv[1:]
        exec(compile(open(argv[0]).read(), argv[0], 'exec')) in local
        return

    try:
        try:
            try:
                # ipython >= 1.0
                from IPython.terminal.embed import \
                    InteractiveShellEmbed
            except ImportError:
                # ipython >= 0.11
                from IPython.frontend.terminal.embed import \
                    InteractiveShellEmbed
            try:
                # ipython >= 4
                from traitlets.config.loader import Config
            except ImportError:
                # ipython >= 0.11
                from IPython.config.loader import Config
            cfg = Config()
            try:
                # >= 0.12
                cfg.PromptManager.in_template = "Snimpy [\\#]> "
                cfg.PromptManager.out_template = "Snimpy [\\#]: "
            except ImportError:
                # 0.11
                cfg.InteractiveShellEmbed.prompt_in1 = "Snimpy [\\#]> "
                cfg.InteractiveShellEmbed.prompt_out = "Snimpy [\\#]: "
            if conf.ipythonprofile:
                cfg.InteractiveShellEmbed.profile = conf.ipythonprofile
            shell = InteractiveShellEmbed(
                config=cfg,
                banner1=banner,
                user_ns=local)
            # Not interested by traceback in this module
            shell.InteractiveTB.tb_offset += 1
        except ImportError:
            # ipython < 0.11
            from IPython.Shell import IPShellEmbed
            argv = ["-prompt_in1", "Snimpy [\\#]> ",
                    "-prompt_out", "Snimpy [\\#]: "]
            if conf.ipythonprofile:
                argv += ["-profile", conf.ipythonprofile]
            shell = IPShellEmbed(argv=argv,
                                 banner=banner, user_ns=local)
            # Not interested by traceback in this module
            shell.IP.InteractiveTB.tb_offset += 1
    except ImportError:
        shell = None

    if shell and conf.ipython:
        shell()
    else:
        try:
            import rlcompleter
            import readline
        except ImportError:
            readline = None
        if readline:
            if conf.histfile:
                try:
                    readline.read_history_file(
                        os.path.expanduser(conf.histfile))
                except IOError:
                    pass
                atexit.register(lambda: readline.write_history_file(
                    os.path.expanduser(conf.histfile)))

            readline.set_completer(rlcompleter.Completer(local).complete)
            readline.parse_and_bind("tab: menu-complete")
        sys.ps1 = conf.prompt
        code.interact(banner=banner, local=local)
예제 #40
0
#!/usr/bin/python
from snimpy.manager import Manager as M
from snimpy.manager import load

load("/usr/share/snmp/mibs/IF-MIB.mib")
m = M("ipmi-sw01", 'snmp-com-ro', 2)
print m.ifTable
import config
import time

INFLUX = influxdb.InfluxDBClient(
    config.INFLUX_HOST,
    config.INFLUX_PORT,
    config.INFLUX_USER,
    config.INFLUX_PASSWORD,
    config.INFLUX_DATABASE,
)

try:
    res = INFLUX.create_database(config.INFLUX_DATABASE)
except: pass

load("/app/UPSMonitor/RFC1155-SMI.txt")
load("/app/UPSMonitor/RFC-1215")
load("/app/UPSMonitor/RFC-1212-MIB.txt")
load("/app/UPSMonitor/RFC1213-MIB.txt")
load("/app/UPSMonitor/stdupsv1.mib")
m = M("172.16.14.36", "NARpublic", 1)

model = m.upsIdentModel
manuf = m.upsIdentManufacturer

def job():
    points = []
    points.append(dict(
        measurement="ups_battery_voltage",
        tags=dict(
            model=model,
예제 #42
0
import time

INFLUX = influxdb.InfluxDBClient(
    config.INFLUX_HOST,
    config.INFLUX_PORT,
    config.INFLUX_USER,
    config.INFLUX_PASSWORD,
    config.INFLUX_DATABASE,
)

try:
    res = INFLUX.create_database(config.INFLUX_DATABASE)
except:
    pass

load("/app/UPSMonitor/RFC1155-SMI.txt")
load("/app/UPSMonitor/RFC-1215")
load("/app/UPSMonitor/RFC-1212-MIB.txt")
load("/app/UPSMonitor/RFC1213-MIB.txt")
load("/app/UPSMonitor/stdupsv1.mib")
m = M("172.16.14.36", "NARpublic", 1)

model = m.upsIdentModel
manuf = m.upsIdentManufacturer


def job():
    points = []
    points.append(
        dict(measurement="ups_battery_voltage",
             tags=dict(model=model, manufacturer=manuf),