def setUp(self):
	global testenv, agent

	testenv = netsnmpTestEnv()

	# Create a new netsnmpAgent instance which
	# - connects to the net-snmp test environment's snmpd instance
	# - uses its statedir
	# - loads the TEST-MIB from our tests directory
	testMIBPath = os.path.abspath(os.path.dirname(__file__)) + \
				  "/TEST-MIB.txt"
	agent = netsnmpagent.netsnmpAgent(
		AgentName      = "netsnmpAgentTestAgent",
		MasterSocket   = testenv.mastersocket,
		PersistenceDir = testenv.statedir,
		MIBFiles       = [ testMIBPath ],
	)

	# Test OIDs for Unsigned32 scalar type
	agent.Unsigned32(
		oidstr = "TEST-MIB::testUnsigned32NoInitval",
	)

	agent.Unsigned32(
		oidstr  = "TEST-MIB::testUnsigned32ZeroInitval",
		initval = 0,
	)

	agent.Unsigned32(
		oidstr  = "TEST-MIB::testUnsigned32MinusOneInitval",
		initval = -1,
	)

	agent.Unsigned32(
		oidstr  = "TEST-MIB::testUnsigned32MaxInitval",
		initval = 4294967295,
	)

	agent.Unsigned32(
		oidstr   = "TEST-MIB::testUnsigned32ReadOnly",
		writable = False,
	)

	# Connect to master snmpd instance
	agent.start()

	# Create a separate thread to implement the absolutely most
	# minimalistic possible agent doing nothing but request handling
	agent.loop = True
	def RequestHandler():
		while self.agent.loop:
			agent.check_and_process(False)

	agent.thread = threading.Thread(target=RequestHandler)
	agent.thread.daemon = True
	agent.thread.start()
Пример #2
0
def setUp(self):
    global testenv, agent

    testenv = netsnmpTestEnv()

    # Create a new netsnmpAgent instance which
    # - connects to the net-snmp test environment's snmpd instance
    # - uses its statedir
    # - loads the TEST-MIB from our tests directory
    testMIBPath = os.path.abspath(os.path.dirname(__file__)) + \
         "/TEST-MIB.txt"
    agent = netsnmpagent.netsnmpAgent(
        AgentName="netsnmpAgentTestAgent",
        MasterSocket=testenv.mastersocket,
        PersistenceDir=testenv.statedir,
        MIBFiles=[testMIBPath],
    )

    # Test OIDs for Unsigned32 scalar type
    agent.Unsigned32(oidstr="TEST-MIB::testUnsigned32NoInitval", )

    agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32ZeroInitval",
        initval=0,
    )

    agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32MinusOneInitval",
        initval=-1,
    )

    agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32MaxInitval",
        initval=4294967295,
    )

    agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32ReadOnly",
        writable=False,
    )

    # Connect to master snmpd instance
    agent.start()

    # Create a separate thread to implement the absolutely most
    # minimalistic possible agent doing nothing but request handling
    agent.loop = True

    def RequestHandler():
        while self.agent.loop:
            agent.check_and_process(False)

    agent.thread = threading.Thread(target=RequestHandler)
    agent.thread.daemon = True
    agent.thread.start()
Пример #3
0
    def _create_agent(self, mastersocket, persistencedir):
        mibs_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "mibs")
        mib_file = os.path.join(mibs_path, "LBA-MIB.mib")

        agent = netsnmpagent.netsnmpAgent(
            AgentName      = "LBA_Agent",
            MasterSocket   = mastersocket,
            PersistenceDir = persistencedir,
            MIBFiles       = [mib_file],
        )

        return agent
Пример #4
0
    def _create_snmp_objects(self):
        try:
            self.agent = netsnmpagent.netsnmpAgent(
                AgentName="OpenVpnAgent",
                MasterSocket=self.options.mastersocket,
                PersistenceDir=self.options.persistencedir,
                MIBFiles=[os.path.abspath(os.path.dirname(sys.argv[0])) +
                          "/openvpn.mib"]
            )
        except netsnmpagent.netsnmpAgentException as e:
            logger.critical(e)
            sys.exit(1)

        self.snmp = dict()
        self.snmp['serverTable'] = self.agent.Table(
            oidstr="OPENVPN-MIB::openvpnServerTable",
            indexes=[
                self.agent.Unsigned32()
            ],
            columns=[
                (2, self.agent.DisplayString()),
                (3, self.agent.Unsigned32(0)),
                (4, self.agent.Unsigned32(0)),
                (5, self.agent.Unsigned32(0))
            ],
            counterobj=self.agent.Unsigned32(
                oidstr="OPENVPN-MIB::openvpnServerTableLength"
            )
        )

        self.snmp['userTable'] = self.agent.Table(
            oidstr="OPENVPN-MIB::openvpnUserTable",
            indexes=[
                self.agent.Unsigned32()
            ],
            columns=[
                (2, self.agent.DisplayString()),
                (3, self.agent.DisplayString()),
                (4, self.agent.Unsigned32(0)),
                (5, self.agent.Unsigned32(0))
            ],
            counterobj=self.agent.Unsigned32(
                oidstr="OPENVPN-MIB::openvpnUserTableLength"
            )
        )
        try:
            self.agent.start()
        except netsnmpagent.netsnmpAgentException as e:
            logger.critical(e)
            sys.exit(1)

        logger.info("AgentX connection to snmpd established.")
Пример #5
0
    def _create_agent(self, mastersocket, persistencedir):
        mibs_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 "mibs")
        mib_file = os.path.join(mibs_path, "LBA-MIB.mib")

        agent = netsnmpagent.netsnmpAgent(
            AgentName="LBA_Agent",
            MasterSocket=mastersocket,
            PersistenceDir=persistencedir,
            MIBFiles=[mib_file],
        )

        return agent
Пример #6
0
def eventserver():
	from netsnmpagent import netsnmpAgent
	agent = netsnmpAgent(
			MasterSocket   = "/var/run/agentx-master",
		)
	while True:
		for cEventMem in cEventList:
			time.sleep(5)
			rc = cEventMem.getEvent()
			if rc == 1:
				if cEventMem.get_snmptrap() == 1:
					cEventMem.action2send_snmptrap(agent)
				if cEventMem.get_mail() == 1:
					cEventMem.action2send_mail()
				if cEventMem.get_loadconfig() == 1:
					cEventMem.action2load_config()
 def create_agent(self, options):
     # First, create an instance of the netsnmpAgent class. We specify the
     # fully-qualified path to NETSCAN-MIB.my ourselves here, so that you
     # don't have to copy the MIB to /usr/share/snmp/mibs.
     try:
         agent = netsnmpagent.netsnmpAgent(
             AgentName      = "NetscanAgent",
             MasterSocket   = options.mastersocket,
             PersistenceDir = options.persistencedir,
             MIBFiles       = [ os.path.abspath(os.path.dirname(sys.argv[0])) +
                             "/NETSCAN-MIB.my" ]
         )
     except netsnmpagent.netsnmpAgentException as e:
         print("NetscanMIBagent: {0}".format(e))
         sys.exit(1)
     return agent
def test_Instantiation():
	""" Instantiation without exceptions and within reasonable time """

	global logbuf, agent

	# Create a buffer to capture net-snmp log messages
	logbuf = []

	# Define a custom net-snmp logging handler
	def NetSNMPLogHandler(msgprio, msgtext):
		global logbuf

		# Store net-snmp log messages in our buffer so we can have a look
		# at them later on
		logbuf.append({
			"time": time.clock(),
			"prio": msgprio,
			"text": msgtext
		})

		# Also print them out to stdout as the default log handler would, nose
		# will capture the output and display it if a test fails
		print("[{0}] {1}".format(msgprio, msgtext))

	# Create a new netsnmpAgent instance which
	# - connects to the net-snmp test environment's snmpd instance
	# - uses its statedir
	# - loads the TEST-MIB from our tests directory
	# - uses the net-snmp logging handler defined above
	testMIBPath = os.path.abspath(os.path.dirname(__file__)) + \
				  "/TEST-MIB.txt"
	agent = netsnmpagent.netsnmpAgent(
		AgentName      = "netsnmpAgentTestAgent",
		MasterSocket   = testenv.mastersocket,
		PersistenceDir = testenv.statedir,
		MIBFiles       = [ testMIBPath ],
		LogHandler     = NetSNMPLogHandler,
	)
def test_Instantiation():
	""" Instantiation without exceptions and within reasonable time """

	global logbuf, agent

	# Create a buffer to capture net-snmp log messages
	logbuf = []

	# Define a custom net-snmp logging handler
	def NetSNMPLogHandler(msgprio, msgtext):
		global logbuf

		# Store net-snmp log messages in our buffer so we can have a look
		# at them later on
		logbuf.append({
			"time": time.clock(),
			"prio": msgprio,
			"text": msgtext,
		})

		# Also print them out to stdout as the default log handler would, nose
		# will capture the output and display it if a test fails
		print "[{0}] {1}".format(msgprio, msgtext)

	# Create a new netsnmpAgent instance which
	# - connects to the net-snmp test environment's snmpd instance
	# - uses its statedir
	# - loads the TEST-MIB from our tests directory
	# - uses the net-snmp logging handler defined above
	testMIBPath = os.path.abspath(os.path.dirname(__file__)) + \
				  "/TEST-MIB.txt"
	agent = netsnmpagent.netsnmpAgent(
		AgentName      = "netsnmpAgentTestAgent",
		MasterSocket   = testenv.mastersocket,
		PersistenceDir = testenv.statedir,
		MIBFiles       = [ testMIBPath ],
		LogHandler     = NetSNMPLogHandler,
	)
Пример #10
0
    arc_read = arc_hits + arc_misses
    if arc_read > 0:
        hit_percent = float(100 * arc_hits / arc_read)
        miss_percent = 100 - hit_percent
        return miss_percent
    return 0


mib_builder = pysnmp.smi.builder.MibBuilder()
mib_sources = mib_builder.getMibSources() + (pysnmp.smi.builder.DirMibSource("/usr/local/share/pysnmp/mibs"),)
mib_builder.setMibSources(*mib_sources)
mib_builder.loadModules("FREENAS-MIB")
zpool_health_type = mib_builder.importSymbols("FREENAS-MIB", "ZPoolHealthType")[0]

agent = netsnmpagent.netsnmpAgent(
    AgentName="FreeNASAgent",
    MIBFiles=["/usr/local/share/snmp/mibs/FREENAS-MIB.txt"],
)

zpool_table = agent.Table(
    oidstr="FREENAS-MIB::zpoolTable",
    indexes=[
        agent.Integer32()
    ],
    columns=[
        (2, agent.DisplayString()),
        (3, agent.Integer32()),
        (4, agent.Integer32()),
        (5, agent.Integer32()),
        (6, agent.Integer32()),
        (7, agent.Integer32()),
        (8, agent.Counter64()),
			time.strftime("%T", time.localtime(time.time())),
			"{0}: {1}".format(funcname, msg)
		)
	print logmsg

def LogNetSnmpMsg(priority, msg):
	""" Log handler for log messages generated by net-snmp code. """

	LogMsg("[{0}] {1}.".format(priority, msg))

# Create an instance of the netsnmpAgent class
try:
	agent = netsnmpagent.netsnmpAgent(
		AgentName      = "ThreadingAgent",
		MasterSocket   = options.mastersocket,
		PersistenceDir = options.persistencedir,
		MIBFiles       = [ os.path.abspath(os.path.dirname(sys.argv[0])) +
		                   "/THREADING-MIB.txt" ],
		LogHandler     = LogNetSnmpMsg,
	)
except netsnmpagent.netsnmpAgentException as e:
	print "{0}: {1}".format(prgname, e)
	sys.exit(1)

# Register the only SNMP object we server, a DisplayString
threadingString = agent.DisplayString(
	oidstr  = "THREADING-MIB::threadingString",
	initval = "<No data available yet>"
)

def UpdateSNMPObjs():
	""" Function that does the actual data update. """
Пример #12
0
	help="Sets the path to the persistence directory",
	default="/var/lib/net-snmp"
)
(options, args) = parser.parse_args()

# Get terminal width for usage with pprint
rows, columns = os.popen("stty size", "r").read().split()

# First, create an instance of the netsnmpAgent class. We specify the
# fully-qualified path to SIMPLE-MIB.txt ourselves here, so that you
# don't have to copy the MIB to /usr/share/snmp/mibs.
try:
	agent = netsnmpagent.netsnmpAgent(
		AgentName="SimpleAgent",
		MasterSocket=options.mastersocket,
		PersistenceDir=options.persistencedir,
		MIBFiles=[ os.path.abspath(os.path.dirname(sys.argv[0])) +
		                   "/SIMPLE-MIB.txt" ]
	)
except netsnmpagent.netsnmpAgentException as e:
	print("{0}: {1}".format(prgname, e))
	sys.exit(1)

# Then we create all SNMP scalar variables we're willing to serve.
simpleInteger = agent.Integer32(
	oidstr="SIMPLE-MIB::simpleInteger"
)
simpleIntegerContext1 = agent.Integer32(
	oidstr="SIMPLE-MIB::simpleInteger",
	context="context1",
	initval=200,
Пример #13
0
def setUp(self):
    global testenv, agent
    global settableInteger32, settableUnsigned32, settableTimeTicks
    global settableOctetString

    testenv = netsnmpTestEnv()

    # Create a new netsnmpAgent instance which
    # - connects to the net-snmp test environment's snmpd instance
    # - uses its statedir
    # - loads the TEST-MIB from our tests directory
    testMIBPath = os.path.abspath(os.path.dirname(__file__)) + \
         "/TEST-MIB.txt"
    agent = netsnmpagent.netsnmpAgent(
        AgentName="netsnmpAgentTestAgent",
        MasterSocket=testenv.mastersocket,
        PersistenceDir=testenv.statedir,
        MIBFiles=[testMIBPath],
    )

    # Test OIDs for Integer32 scalar type
    settableInteger32 = agent.Integer32(
        oidstr="TEST-MIB::testInteger32NoInitval", )

    agent.Integer32(
        oidstr="TEST-MIB::testInteger32ZeroInitval",
        initval=0,
    )

    agent.Integer32(
        oidstr="TEST-MIB::testInteger32MinusOneInitval",
        initval=-1,
    )

    agent.Integer32(
        oidstr="TEST-MIB::testInteger32MinInitval",
        initval=-2147483648,
    )

    agent.Integer32(
        oidstr="TEST-MIB::testInteger32MinMinusOneInitval",
        initval=-2147483649,
    )

    agent.Integer32(
        oidstr="TEST-MIB::testInteger32OneInitval",
        initval=1,
    )

    agent.Integer32(
        oidstr="TEST-MIB::testInteger32MaxInitval",
        initval=2147483647,
    )

    agent.Integer32(
        oidstr="TEST-MIB::testInteger32MaxPlusOneInitval",
        initval=2147483648,
    )

    agent.Integer32(
        oidstr="TEST-MIB::testInteger32ReadOnly",
        writable=False,
    )

    # Test OIDs for Unsigned32 scalar type
    settableUnsigned32 = agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32NoInitval", )

    agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32ZeroInitval",
        initval=0,
    )

    agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32MinusOneInitval",
        initval=-1,
    )

    agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32OneInitval",
        initval=1,
    )

    agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32MaxInitval",
        initval=4294967295,
    )

    agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32MaxPlusOneInitval",
        initval=4294967296,
    )

    agent.Unsigned32(
        oidstr="TEST-MIB::testUnsigned32ReadOnly",
        writable=False,
    )

    # Test OIDs for Counter32 scalar type
    agent.Counter32(oidstr="TEST-MIB::testCounter32NoInitval", )

    agent.Counter32(
        oidstr="TEST-MIB::testCounter32ZeroInitval",
        initval=0,
    )

    agent.Counter32(
        oidstr="TEST-MIB::testCounter32MinusOneInitval",
        initval=-1,
    )

    agent.Counter32(
        oidstr="TEST-MIB::testCounter32OneInitval",
        initval=1,
    )

    agent.Counter32(
        oidstr="TEST-MIB::testCounter32MaxInitval",
        initval=4294967295,
    )

    agent.Counter32(
        oidstr="TEST-MIB::testCounter32MaxPlusOneInitval",
        initval=4294967296,
    )

    # Test OIDs for Counter64 scalar type
    agent.Counter64(oidstr="TEST-MIB::testCounter64NoInitval", )

    agent.Counter64(
        oidstr="TEST-MIB::testCounter64ZeroInitval",
        initval=0,
    )

    agent.Counter64(
        oidstr="TEST-MIB::testCounter64MinusOneInitval",
        initval=-1,
    )

    agent.Counter64(
        oidstr="TEST-MIB::testCounter64OneInitval",
        initval=1,
    )

    agent.Counter64(
        oidstr="TEST-MIB::testCounter64MaxInitval",
        initval=18446744073709551615,
    )

    agent.Counter64(
        oidstr="TEST-MIB::testCounter64MaxPlusOneInitval",
        initval=18446744073709551616,
    )

    # Test OIDs for TimeTicks scalar type
    settableTimeTicks = agent.TimeTicks(
        oidstr="TEST-MIB::testTimeTicksNoInitval", )

    agent.TimeTicks(
        oidstr="TEST-MIB::testTimeTicksZeroInitval",
        initval=0,
    )

    agent.TimeTicks(
        oidstr="TEST-MIB::testTimeTicksMinusOneInitval",
        initval=-1,
    )

    agent.TimeTicks(
        oidstr="TEST-MIB::testTimeTicksOneInitval",
        initval=1,
    )

    agent.TimeTicks(
        oidstr="TEST-MIB::testTimeTicksMaxInitval",
        initval=4294967295,
    )

    agent.TimeTicks(
        oidstr="TEST-MIB::testTimeTicksMaxPlusOneInitval",
        initval=4294967296,
    )

    agent.TimeTicks(
        oidstr="TEST-MIB::testTimeTicksReadOnly",
        writable=False,
    )

    # Test OIDs for OctetString scalar type
    settableOctetString = agent.OctetString(
        oidstr="TEST-MIB::testOctetStringNoInitval", )

    agent.OctetString(
        oidstr="TEST-MIB::testOctetStringEmptyInitval",
        initval="",
    )

    agent.OctetString(
        oidstr="TEST-MIB::testOctetStringOneASCIICharInitval",
        initval="A",
    )

    agent.OctetString(
        oidstr="TEST-MIB::testOctetStringOneUTF8CharInitval",
        initval="Ä",
    )

    agent.OctetString(
        oidstr="TEST-MIB::testOctetString255ASCIICharsInitval",
        initval="A" * 255,
    )

    agent.OctetString(
        oidstr="TEST-MIB::testOctetString255UTF8CharsInitval",
        initval="Ä" * 255,
    )

    agent.OctetString(
        oidstr="TEST-MIB::testOctetString256ASCIICharsInitval",
        initval="A" * 256,
    )

    agent.OctetString(
        oidstr="TEST-MIB::testOctetString256UTF8CharsInitval",
        initval="Ä" * 256,
    )

    # Connect to master snmpd instance
    agent.start()

    # Create a separate thread to implement the absolutely most
    # minimalistic possible agent doing nothing but request handling
    agent.loop = True

    def RequestHandler():
        while self.agent.loop:
            agent.check_and_process(False)

    agent.thread = threading.Thread(target=RequestHandler)
    agent.thread.daemon = True
    agent.thread.start()
def setUp(self):
	global testenv, agent
	global settableInteger32, settableUnsigned32, settableTimeTicks
	global settableOctetString, settableDisplayString

	testenv = netsnmpTestEnv()

	# Create a new netsnmpAgent instance which
	# - connects to the net-snmp test environment's snmpd instance
	# - uses its statedir
	# - loads the TEST-MIB from our tests directory
	testMIBPath = os.path.abspath(os.path.dirname(__file__)) + \
				  "/TEST-MIB.txt"
	agent = netsnmpagent.netsnmpAgent(
		AgentName      = "netsnmpAgentTestAgent",
		MasterSocket   = testenv.mastersocket,
		PersistenceDir = testenv.statedir,
		MIBFiles       = [ testMIBPath ],
	)

	# Test OIDs for Integer32 scalar type
	settableInteger32 = agent.Integer32(
		oidstr = "TEST-MIB::testInteger32NoInitval",
	)

	agent.Integer32(
		oidstr  = "TEST-MIB::testInteger32ZeroInitval",
		initval = 0,
	)

	agent.Integer32(
		oidstr  = "TEST-MIB::testInteger32MinusOneInitval",
		initval = -1,
	)

	agent.Integer32(
		oidstr  = "TEST-MIB::testInteger32MinInitval",
		initval = -2147483648,
	)

	agent.Integer32(
		oidstr  = "TEST-MIB::testInteger32MinMinusOneInitval",
		initval = -2147483649,
	)

	agent.Integer32(
		oidstr  = "TEST-MIB::testInteger32OneInitval",
		initval = 1,
	)

	agent.Integer32(
		oidstr  = "TEST-MIB::testInteger32MaxInitval",
		initval = 2147483647,
	)

	agent.Integer32(
		oidstr  = "TEST-MIB::testInteger32MaxPlusOneInitval",
		initval = 2147483648,
	)

	agent.Integer32(
		oidstr   = "TEST-MIB::testInteger32ReadOnly",
		writable = False,
	)

	# Test OIDs for Unsigned32 scalar type
	settableUnsigned32 = agent.Unsigned32(
		oidstr = "TEST-MIB::testUnsigned32NoInitval",
	)

	agent.Unsigned32(
		oidstr  = "TEST-MIB::testUnsigned32ZeroInitval",
		initval = 0,
	)

	agent.Unsigned32(
		oidstr  = "TEST-MIB::testUnsigned32MinusOneInitval",
		initval = -1,
	)

	agent.Unsigned32(
		oidstr  = "TEST-MIB::testUnsigned32OneInitval",
		initval = 1,
	)

	agent.Unsigned32(
		oidstr  = "TEST-MIB::testUnsigned32MaxInitval",
		initval = 4294967295,
	)

	agent.Unsigned32(
		oidstr  = "TEST-MIB::testUnsigned32MaxPlusOneInitval",
		initval = 4294967296,
	)

	agent.Unsigned32(
		oidstr   = "TEST-MIB::testUnsigned32ReadOnly",
		writable = False,
	)

	# Test OIDs for Counter32 scalar type
	agent.Counter32(
		oidstr = "TEST-MIB::testCounter32NoInitval",
	)

	agent.Counter32(
		oidstr  = "TEST-MIB::testCounter32ZeroInitval",
		initval = 0,
	)

	agent.Counter32(
		oidstr  = "TEST-MIB::testCounter32MinusOneInitval",
		initval = -1,
	)

	agent.Counter32(
		oidstr  = "TEST-MIB::testCounter32OneInitval",
		initval = 1,
	)

	agent.Counter32(
		oidstr  = "TEST-MIB::testCounter32MaxInitval",
		initval = 4294967295,
	)

	agent.Counter32(
		oidstr  = "TEST-MIB::testCounter32MaxPlusOneInitval",
		initval = 4294967296,
	)

	# Test OIDs for Counter64 scalar type
	agent.Counter64(
		oidstr = "TEST-MIB::testCounter64NoInitval",
	)

	agent.Counter64(
		oidstr  = "TEST-MIB::testCounter64ZeroInitval",
		initval = 0,
	)

	agent.Counter64(
		oidstr  = "TEST-MIB::testCounter64MinusOneInitval",
		initval = -1,
	)

	agent.Counter64(
		oidstr  = "TEST-MIB::testCounter64OneInitval",
		initval = 1,
	)

	agent.Counter64(
		oidstr  = "TEST-MIB::testCounter64MaxInitval",
		initval = 18446744073709551615,
	)

	agent.Counter64(
		oidstr  = "TEST-MIB::testCounter64MaxPlusOneInitval",
		initval = 18446744073709551616,
	)

	# Test OIDs for Gauge32 scalar type
	agent.Gauge32(
		oidstr = "TEST-MIB::testGauge32NoInitval",
	)

	agent.Gauge32(
		oidstr  = "TEST-MIB::testGauge32ZeroInitval",
		initval = 0,
	)

	agent.Gauge32(
		oidstr  = "TEST-MIB::testGauge32MinusOneInitval",
		initval = -1,
	)

	agent.Gauge32(
		oidstr  = "TEST-MIB::testGauge32OneInitval",
		initval = 1,
	)

	agent.Gauge32(
		oidstr  = "TEST-MIB::testGauge32MaxInitval",
		initval = 4294967295,
	)

	agent.Gauge32(
		oidstr  = "TEST-MIB::testGauge32MaxPlusOneInitval",
		initval = 4294967296,
	)

	# Test OIDs for TimeTicks scalar type
	settableTimeTicks = agent.TimeTicks(
		oidstr = "TEST-MIB::testTimeTicksNoInitval",
	)

	agent.TimeTicks(
		oidstr  = "TEST-MIB::testTimeTicksZeroInitval",
		initval = 0,
	)

	agent.TimeTicks(
		oidstr  = "TEST-MIB::testTimeTicksMinusOneInitval",
		initval = -1,
	)

	agent.TimeTicks(
		oidstr  = "TEST-MIB::testTimeTicksOneInitval",
		initval = 1,
	)

	agent.TimeTicks(
		oidstr  = "TEST-MIB::testTimeTicksMaxInitval",
		initval = 4294967295,
	)

	agent.TimeTicks(
		oidstr  = "TEST-MIB::testTimeTicksMaxPlusOneInitval",
		initval = 4294967296,
	)

	agent.TimeTicks(
		oidstr   = "TEST-MIB::testTimeTicksReadOnly",
		writable = False,
	)

	# Test OIDs for IpAddress scalar type
	settableIpAddress = agent.IpAddress(
		oidstr = "TEST-MIB::testIpAddressNoInitval",
	)

	agent.IpAddress(
		oidstr = "TEST-MIB::testIpAddressEmptyInitval",
		initval = ""
	)

	agent.IpAddress(
		oidstr = "TEST-MIB::testIpAddress1234Initval",
		initval = "1.2.3.4"
	)

	# Test OIDs for TruthValue scalar type
	settableTruthValue = agent.TruthValue(
		oidstr = "TEST-MIB::testTruthValueNoInitval",
	)

	agent.TruthValue(
		oidstr  = "TEST-MIB::testTruthValueFalseInitval",
		initval = False,
	)

	agent.TruthValue(
		oidstr  = "TEST-MIB::testTruthValueTrueInitval",
		initval = True,
	)

	# Test OIDs for Float scalar type
	settableFloat = agent.Float(
		oidstr = "TEST-MIB::testFloatNoInitval",
	)

	agent.Float(
		oidstr  = "TEST-MIB::testFloatZeroPointZeroInitval",
		initval = 0.0,
	)

	agent.Float(
		oidstr  = "TEST-MIB::testFloatZeroPointOneInitval",
		initval = 0.1,
	)

	agent.Float(
		oidstr  = "TEST-MIB::testFloatOnePointTwoInitval",
		initval = 1.2,
	)

	agent.Float(
		oidstr  = "TEST-MIB::testFloatMinusZeroPointOneInitval",
		initval = -0.1,
	)

	agent.Float(
		oidstr  = "TEST-MIB::testFloatMinusOnePointTwoInitval",
		initval = -1.2,
	)

	# Test OIDs for OctetString scalar type
	settableOctetString = agent.OctetString(
		oidstr = "TEST-MIB::testOctetStringNoInitval",
	)

	agent.OctetString(
		oidstr  = "TEST-MIB::testOctetStringEmptyInitval",
		initval = "",
	)

	agent.OctetString(
		oidstr  = "TEST-MIB::testOctetStringOneASCIICharInitval",
		initval = "A",
	)

	agent.OctetString(
		oidstr  = "TEST-MIB::testOctetStringOneUTF8CharInitval",
		initval = "Ä",
	)

	agent.OctetString(
		oidstr  = "TEST-MIB::testOctetString255ASCIICharsInitval",
		initval = "A" * 255,
	)

	agent.OctetString(
		oidstr  = "TEST-MIB::testOctetString255UTF8CharsInitval",
		initval = "Ä" * 255,
	)

	agent.OctetString(
		oidstr  = "TEST-MIB::testOctetString256ASCIICharsInitval",
		initval = "A" * 256,
	)

	agent.OctetString(
		oidstr  = "TEST-MIB::testOctetString256UTF8CharsInitval",
		initval = "Ä" * 256,
	)

	# Test OIDs for DisplayString scalar type
	settableDisplayString = agent.DisplayString(
		oidstr = "TEST-MIB::testDisplayStringNoInitval",
	)

	agent.DisplayString(
		oidstr  = "TEST-MIB::testDisplayStringEmptyInitval",
		initval = "",
	)

	agent.DisplayString(
		oidstr  = "TEST-MIB::testDisplayStringOneASCIICharInitval",
		initval = "A",
	)

	agent.DisplayString(
		oidstr  = "TEST-MIB::testDisplayString255ASCIICharsInitval",
		initval = "A" * 255,
	)

	agent.DisplayString(
		oidstr  = "TEST-MIB::testDisplayString256ASCIICharsInitval",
		initval = "A" * 256,
	)

	# Connect to master snmpd instance
	agent.start()

	# Create a separate thread to implement the absolutely most
	# minimalistic possible agent doing nothing but request handling
	agent.loop = True
	def RequestHandler():
		while self.agent.loop:
			agent.check_and_process(False)

	agent.thread = threading.Thread(target=RequestHandler)
	agent.thread.daemon = True
	agent.thread.start()
Пример #15
0
parser.add_option("-p",
                  "--persistencedir",
                  dest="persistencedir",
                  help="Sets the path to the persistence directory",
                  default="/var/lib/net-snmp")
(options, args) = parser.parse_args()

# Get terminal width for usage with pprint
rows, columns = os.popen("stty size", "r").read().split()

# First, create an instance of the netsnmpAgent class. We specify the
# fully-qualified path to AFINITI-TEST-MIB.txt ourselves here, so that you
# don't have to copy the MIB to /usr/share/snmp/mibs.
try:
    agent = netsnmpagent.netsnmpAgent(AgentName="Agent",
                                      MasterSocket=options.mastersocket,
                                      PersistenceDir=options.persistencedir,
                                      MIBFiles=["AFINITI-TEST-MIB.txt"])
except netsnmpagent.netsnmpAgentException as e:
    print("{0}: {1}".format(prgname, e))
    sys.exit(1)

# Then we create all SNMP variables we're willing to serve.
versionNumber = agent.OctetString(oidstr="AFINITI-TEST-MIB::versionNumber",
                                  initval="6.6.1")
latestSignal = agent.OctetString(oidstr="AFINITI-TEST-MIB::latestSignal",
                                 initval=fetchLatestSignal())
diskSpace = agent.Counter64(oidstr="AFINITI-TEST-MIB::diskSpace",
                            initval=shutil.disk_usage("/var/log").used)

# Finally, we tell the agent to "start". This actually connects the
# agent to the master agent.
Пример #16
0
	dest="persistencedir",
	help="Sets the path to the persistence directory",
	default="/var/lib/net-snmp"
)
(options, args) = parser.parse_args()

# Get terminal width for usage with pprint
rows,columns = os.popen("stty size", "r").read().split()

# First, create an instance of the netsnmpAgent class. We specify the
# fully-qualified path to SIMPLE-MIB.txt ourselves here, so that you
# don't have to copy the MIB to /usr/share/snmp/mibs.
try:
	agent = netsnmpagent.netsnmpAgent(
		AgentName      = "SimpleAgent",
		MasterSocket   = options.mastersocket,
		PersistenceDir = options.persistencedir,
		MIBFiles       = [ "/usr/share/snmp/mibs/SIMPLE-MIB.mib" ]
	)
except netsnmpagent.netsnmpAgentException as e:
	print "{0}: {1}".format(prgname, e)
	sys.exit(1)

# Then we create all SNMP scalar variables we're willing to serve.
simpleInteger = agent.Integer32(
	oidstr = "SIMPLE-MIB::simpleInteger"
)
simpleIntegerContext1 = agent.Integer32(
	oidstr = "SIMPLE-MIB::simpleInteger",
	context = "context1",
	initval = 200,
)
			time.strftime("%T", time.localtime(time.time())),
			"{0}: {1}".format(funcname, msg)
		)
	print logmsg

def LogNetSnmpMsg(priority, msg):
	""" Log handler for log messages generated by net-snmp code. """

	LogMsg("[{0}] {1}.".format(priority, msg))

# Create an instance of the netsnmpAgent class
try:
	agent = netsnmpagent.netsnmpAgent(
		AgentName      = "systemdAgent",
		MasterSocket   = options.mastersocket,
		PersistenceDir = options.persistencedir,
		MIBFiles       = [ os.path.abspath(os.path.dirname(sys.argv[0])) +
		                   "/NETWORK-SERVICES-MIB.txt" ],
		LogHandler     = LogNetSnmpMsg,
	)
except netsnmpagent.netsnmpAgentException as e:
	print "{0}: {1}".format(prgname, e)
	sys.exit(1)

# Creating the table
applTable = agent.Table(
	oidstr = "NETWORK-SERVICES-MIB::applTable",
	indexes = [
                agent.Integer32()
	],
	columns = [
		(2, agent.OctetString("")),
Пример #18
0
			time.strftime("%T", time.localtime(time.time())),
			"{0}: {1}".format(funcname, msg)
		)
	print logmsg

def LogNetSnmpMsg(priority, msg):
	""" Log handler for log messages generated by net-snmp code. """

	LogMsg("[{0}] {1}.".format(priority, msg))

# Create an instance of the netsnmpAgent class
try:
	agent = netsnmpagent.netsnmpAgent(
		AgentName      = "PrototypeAgent",
		MasterSocket   = options.mastersocket,
		PersistenceDir = options.persistencedir,
		MIBFiles       = [ os.path.abspath(os.path.dirname(sys.argv[0])) +
		                   "/ARPA2-Experimental-DNSSEC-MIBv1.txt" ],
		LogHandler     = LogNetSnmpMsg,
	)
except netsnmpagent.netsnmpAgentException as e:
	print "{0}: {1}".format(prgname, e)
	sys.exit(1)


################################ BEGIN Edit Martin Leucht################################

# actual data we want to feed the MIB

# TODO
dnsseczonecount = 1
Пример #19
0
    print(logmsg)


def LogNetSnmpMsg(priority, msg):
    """ Log handler for log messages generated by net-snmp code. """

    LogMsg("[{0}] {1}.".format(priority, msg))


# Create an instance of the netsnmpAgent class
try:
    agent = netsnmpagent.netsnmpAgent(
        AgentName="ThreadingAgent",
        MasterSocket=options.mastersocket,
        PersistenceDir=options.persistencedir,
        MIBFiles=[
            os.path.abspath(os.path.dirname(sys.argv[0])) +
            "/THREADING-MIB.txt"
        ],
        LogHandler=LogNetSnmpMsg,
    )
except netsnmpagent.netsnmpAgentException as e:
    print("{0}: {1}".format(prgname, e))
    sys.exit(1)

# Register the only SNMP object we server, a DisplayString
threadingString = agent.DisplayString(oidstr="THREADING-MIB::threadingString",
                                      initval="<No data available yet>")


def UpdateSNMPObjs():
    """ Function that does the actual data update. """
Пример #20
0
	help="Sets the path to the persistence directory",
	default="/var/lib/net-snmp"
)
(options, args) = parser.parse_args()

# Get terminal width for usage with pprint
rows,columns = os.popen("stty size", "r").read().split()

# First, create an instance of the netsnmpAgent class. We specify the
# fully-qualified path to SIMPLE-MIB.txt ourselves here, so that you
# don't have to copy the MIB to /usr/share/snmp/mibs.
try:
	agent = netsnmpagent.netsnmpAgent(
		AgentName      = "SimpleAgent",
		MasterSocket   = options.mastersocket,
		PersistenceDir = options.persistencedir,
		MIBFiles       = [ os.path.abspath(os.path.dirname(sys.argv[0])) +
		                   "/SIMPLE-MIB.txt" ]
	)
except netsnmpagent.netsnmpAgentException as e:
	print "{0}: {1}".format(prgname, e)
	sys.exit(1)

# Then we create all SNMP scalar variables we're willing to serve.
simpleInteger = agent.Integer32(
	oidstr = "SIMPLE-MIB::simpleInteger"
)
simpleIntegerContext1 = agent.Integer32(
	oidstr = "SIMPLE-MIB::simpleInteger",
	context = "context1",
	initval = 200,
def initialize(prg_name):
    ###
    #	Init agent
    ###
    try:
        agent = netsnmpagent.netsnmpAgent(
            AgentName=AGENT_CONFIGURATION["agent_name"],
            MasterSocket=AGENT_CONFIGURATION["master_socket"],
            PersistenceDir=AGENT_CONFIGURATION["persistence_dir"])
    except netsnmpagent.netsnmpAgentException as ex:
        logger.error("{0}: {1}".format(prg_name, ex))

    ###
    #	Init table
    ###
    # Init dns statistic per client
    stat_per_client_table = agent.Table(
        oidstr=TableOidStr.STAT_PER_CLIENT,
        indexes=[
            agent.OctetString(),  # client ip
            agent.Integer32()  # bcnDnsStatAgentQryTypes
        ],
        columns=[
            # Columns begin with an index of 2 here because 1 is actually
            # used for the single index column above.
            # We must explicitly specify that the columns should be SNMPSETable.
            (1, agent.OctetString(), True),  # client ip
            (2, agent.Integer32(), True),  # bcnDnsStatAgentQryTypes
            (3, agent.Counter64(), True)  # statistic dns value
        ],
        # Allow adding new records
        extendable=True)

    # Init table of average response time in the last interval (e.g. 1 minute) and are classified by DNS client.
    avg_time_per_client_table = agent.Table(
        oidstr=TableOidStr.AVG_TIME_PER_CLIENT,
        indexes=[
            agent.OctetString()  # client ip
        ],
        columns=[
            (1, agent.OctetString(), True),  # client ip
            (2, agent.Integer32(), True)  # Average time in micro seconds
        ],
        # Allow adding new records
        extendable=True)

    # Init dns statistic per auth dns server
    stat_per_server_table = agent.Table(
        oidstr=TableOidStr.STAT_PER_SERVER,
        indexes=[
            agent.OctetString(),  # Server ip
            agent.Integer32()  # bcnDnsStatAgentQryTypes
        ],
        columns=[
            # Columns begin with an index of 2 here because 1 is actually
            # used for the single index column above.
            (1, agent.OctetString(), True),  # Server ip
            (2, agent.Integer32(), True),  # bcnDnsStatAgentQryTypes
            (3, agent.Counter64(), True)  # statistic dns value
        ],
        # Allow adding new records
        extendable=True)

    # Init table of average response time in the last interval (e.g. 1 minute) and are classified by Authoritative DNS Server or Forwarder.
    avg_time_per_server_table = agent.Table(
        oidstr=TableOidStr.AVG_TIME_PER_SERVER,
        indexes=[
            agent.OctetString()  # server ip
        ],
        columns=[
            (1, agent.OctetString(), True),  # server ip
            (2, agent.Integer32(), True)  # Average time in micro seconds
        ],
        # Allow adding new records
        extendable=True)

    # Init table of statistics per each view from Packetbeat.
    stat_per_view_table = agent.Table(
        oidstr=TableOidStr.STAT_PER_VIEW,
        indexes=[
            agent.DisplayString(),  # view
            agent.Integer32()  # bcnDnsStatAgentQryTypes
        ],
        columns=[
            # Columns begin with an index of 2 here because 1 is actually
            # used for the single index column above.
            (1, agent.DisplayString(), True),  # view
            (2, agent.Integer32(), True),  # bcnDnsStatAgentQryTypes
            (3, agent.Counter64(), True)  # The value of the reported statistic
        ],
        # Allow adding new records
        extendable=True)

    # Init table of average response time in the last interval (e.g. 1 minute) and are classified by view.
    avg_time_per_view_table = agent.Table(
        oidstr=TableOidStr.AVG_TIME_PER_VIEW,
        indexes=[
            agent.DisplayString()  # view
        ],
        columns=[
            (1, agent.DisplayString(), True),  # view
            (2, agent.Integer32(), True)  # Average time in micro seconds
        ],
        # Allow adding new records
        extendable=True)

    # Init table of statistics per each view from the time the BIND service starts running.
    bind_stat_per_view_table = agent.Table(
        oidstr=TableOidStr.BIND_STAT_PER_VIEW,
        indexes=[
            agent.DisplayString(),  # bindView
            agent.Integer32()  # bcnDnsBindStatPerViewAgentQryTypes
        ],
        columns=[
            # Columns begin with an index of 2 here because 1 is actually
            # used for the single index column above.
            (1, agent.DisplayString(), True),  # bindView
            (2, agent.Integer32(), True),  # bcnDnsBindStatPerViewAgentQryTypes
            (3, agent.Counter64(), True
             )  # The value of the reported statistic from bind
        ],
        # Allow adding new records
        extendable=True)

    table = {
        TableOidStr.STAT_PER_CLIENT: {
            "table": stat_per_client_table,
            "table_value": {}
        },
        TableOidStr.AVG_TIME_PER_CLIENT: {
            "table": avg_time_per_client_table
        },
        TableOidStr.STAT_PER_SERVER: {
            "table": stat_per_server_table,
            "table_value": {}
        },
        TableOidStr.AVG_TIME_PER_SERVER: {
            "table": avg_time_per_server_table
        },
        TableOidStr.STAT_PER_VIEW: {
            "table": stat_per_view_table,
            "table_value": {}
        },
        TableOidStr.AVG_TIME_PER_VIEW: {
            "table": avg_time_per_view_table
        },
        TableOidStr.BIND_STAT_PER_VIEW: {
            "table": bind_stat_per_view_table
        }
    }

    return agent, table
Пример #22
0
			time.strftime("%T", time.localtime(time.time())),
			"{0}: {1}".format(funcname, msg)
		)
	print logmsg

def LogNetSnmpMsg(priority, msg):
	""" Log handler for log messages generated by net-snmp code. """

	LogMsg("[{0}] {1}.".format(priority, msg))

# Create an instance of the netsnmpAgent class
try:
	agent = netsnmpagent.netsnmpAgent(
		AgentName      = "PrototypeAgent",
		MasterSocket   = options.mastersocket,
		PersistenceDir = options.persistencedir,
		MIBFiles       = [ os.path.abspath(os.path.dirname(sys.argv[0])) +
		                   "/DNSSEC-MIBv2.txt" ],
		LogHandler     = LogNetSnmpMsg,
	)
except netsnmpagent.netsnmpAgentException as e:
	print "{0}: {1}".format(prgname, e)
	sys.exit(1)


#### Edit ####

# actual data we want to feed the MIB

# TODO
dnsseczonecount = 1