def trap_handler(trap): """Handles a trap. :type trap: nav.snmptrapd.trap.SNMPTrap """ traplogger.debug(trap.trapText()) connection = getConnection('default') handled_by = [] for mod in handlermodules: logger.debug("Giving trap to %s" % str(mod)) try: accepted = mod.handleTrap(trap, config=config) if accepted: handled_by.append(mod.__name__) logger.debug( "Module %s %s trap", mod.__name__, accepted and 'accepted' or 'ignored', ) except Exception as why: logger.exception("Error when handling trap with %s: %s" % (mod.__name__, why)) # Assuming that the handler used the same connection as this # function, we rollback any uncommitted changes. This is to # avoid idling in transactions. connection.rollback() if handled_by: logger.info("v%s trap received from %s, handled by %s", trap.version, trap.src, handled_by) else: logger.info("v%s trap received from %s, no handlers wanted it", trap.version, trap.src)
def verify_event_type(): """ Safe way of verifying that the event- and alarmtypes exist in the database. Should be run when module is imported. """ connection = getConnection('default') cursor = connection.cursor() sql = """ INSERT INTO eventtype ( SELECT 'linkState','Tells us whether a link is up or down.','y' WHERE NOT EXISTS ( SELECT * FROM eventtype WHERE eventtypeid = 'linkState')); INSERT INTO alertType ( SELECT nextval('alerttype_alerttypeid_seq'), 'linkState', 'linkUp', 'Link active' WHERE NOT EXISTS ( SELECT * FROM alerttype WHERE alerttype = 'linkUp')); INSERT INTO alertType ( SELECT nextval('alerttype_alerttypeid_seq'), 'linkState', 'linkDown', 'Link inactive' WHERE NOT EXISTS ( SELECT * FROM alerttype WHERE alerttype = 'linkDown')); """ queries = sql.split(';') for query in queries: if query.rstrip(): cursor.execute(query) connection.commit()
def localhost_using_legacy_db(): """Alternative to the Django-based localhost fixture, for tests that operate on code that uses legacy database connections. """ from nav.db import getConnection conn = getConnection('default') cursor = conn.cursor() sql = """ INSERT INTO netbox (ip, sysname, orgid, roomid, catid) VALUES (%s, %s, %s, %s, %s) RETURNING netboxid; """ cursor.execute( sql, ('127.0.0.1', 'localhost.example.org', 'myorg', 'myroom', 'SRV')) netboxid = cursor.fetchone()[0] conn.commit() yield netboxid print("teardown localhost device using legacy connection") cursor.execute("DELETE FROM netbox WHERE netboxid=%s", (netboxid, )) conn.commit()
def get_subnets(network, min_length=None): """Retrieves all the subnets of the argument ``network''. Arguments: ``min_length'': minimum subnet mask length, defaults to network.prefixlen(). Returns: List with IPy.IP objects """ max_length = 128 if network.version() == 6 else 32 if min_length is None: min_length = network.prefixlen() assert min_length < max_length sql = """ SELECT netaddr FROM prefix WHERE family(netaddr)=%s AND netaddr << %s AND masklen(netaddr) >= %s AND masklen(netaddr) < %s """ args = (network.version(), str(network), min_length, max_length) db_cursor = db.getConnection('default').cursor() db_cursor.execute(sql.strip(), args) db_result = db_cursor.fetchall() return [IP(i[0]) for i in db_result]
def logengine(config, options): verify_singleton(options.quiet) connection = db.getConnection('logger', 'logger') database = connection.cursor() ## initial setup of dictionaries categories = get_categories(database) origins = get_origins(database) types = get_types(database) ## parse priorityexceptions (exceptionorigin, exceptiontype, exceptiontypeorigin) = get_exception_dicts(config) ## add new records _logger.info("Reading new log entries") my_parse_and_insert = swallow_all_but_db_exceptions(parse_and_insert) for line in read_log_lines(config): my_parse_and_insert(line, database, categories, origins, types, exceptionorigin, exceptiontype, exceptiontypeorigin) # Make sure it all sticks connection.commit()
def trap_handler(trap): """Handles a trap. :type trap: SNMPTrap """ _traplogger.debug("%s", trap) connection = getConnection('default') handled_by = [] for mod in handlermodules: _logger.debug("Offering trap (%s) to %s", id(trap), mod) try: accepted = mod.handleTrap(trap, config=config) if accepted: handled_by.append(mod.__name__) _logger.debug( "Module %s %s trap (%s)", mod.__name__, 'accepted' if accepted else 'ignored', id(trap), ) except Exception as why: _logger.exception( "Unhandled exception when handling trap (%s) with %s: %s", id(trap), mod.__name__, why, ) # Assuming that the handler used the same connection as this # function, we rollback any uncommitted changes. This is to # avoid idling in transactions. connection.rollback() _log_trap_handle_result(handled_by, trap)
def verifyEventtype (): """ Safe way of verifying that the event- and alarmtypes exist in the database. Should be run when module is imported. """ db = getConnection('default') c = db.cursor() # NB: Remember to replace the values with the one you need. sql = """ INSERT INTO eventtype ( SELECT 'upsPowerState','UPS running on battery or utility power','y' WHERE NOT EXISTS ( SELECT * FROM eventtype WHERE eventtypeid = 'upsPowerState')); INSERT INTO alertType ( SELECT nextval('alerttype_alerttypeid_seq'), 'upsPowerState', 'upsOnBatteryPower', 'Ups running on battery power' WHERE NOT EXISTS ( SELECT * FROM alerttype WHERE alerttype = 'upsOnBatteryPower')); INSERT INTO alertType ( SELECT nextval('alerttype_alerttypeid_seq'), 'upsPowerState', 'upsOnUtilityPower', 'Ups running on utility power' WHERE NOT EXISTS ( SELECT * FROM alerttype WHERE alerttype = 'upsOnUtilityPower')); """ queries = sql.split(';') for q in queries: if len(q.rstrip()) > 0: c.execute(q) db.commit()
def logengine(config, options): global connection, database verify_singleton(options.quiet) connection = db.getConnection('logger','logger') database = connection.cursor() ## initial setup of dictionaries categories = get_categories(database) origins = get_origins(database) types = get_types(database) ## parse priorityexceptions (exceptionorigin, exceptiontype, exceptiontypeorigin) = get_exception_dicts(config) ## add new records logger.info("Reading new log entries") my_parse_and_insert = swallow_all_but_db_exceptions(parse_and_insert) for line in read_log_lines(config): my_parse_and_insert(line, database, categories, origins, types, exceptionorigin, exceptiontype, exceptiontypeorigin) # Make sure it all sticks connection.commit()
def verifyEventtype(): """ Safe way of verifying that the event- and alarmtypes exist in the database. Should be run when module is imported. """ db = getConnection('default') c = db.cursor() # NB: Remember to replace the values with the one you need. sql = """ INSERT INTO eventtype ( SELECT 'upsPowerState','UPS running on battery or utility power','y' WHERE NOT EXISTS ( SELECT * FROM eventtype WHERE eventtypeid = 'upsPowerState')); INSERT INTO alertType ( SELECT nextval('alerttype_alerttypeid_seq'), 'upsPowerState', 'upsOnBatteryPower', 'Ups running on battery power' WHERE NOT EXISTS ( SELECT * FROM alerttype WHERE alerttype = 'upsOnBatteryPower')); INSERT INTO alertType ( SELECT nextval('alerttype_alerttypeid_seq'), 'upsPowerState', 'upsOnUtilityPower', 'Ups running on utility power' WHERE NOT EXISTS ( SELECT * FROM alerttype WHERE alerttype = 'upsOnUtilityPower')); """ queries = sql.split(';') for q in queries: if q.rstrip(): c.execute(q) db.commit()
def getSubnets(network, min_length=None): """Retrieves all the subnets of the argument ``network''. Arguments: ``min_length'': minimum subnet mask length, defaults to network.prefixlen(). Returns: List with IPy.IP objects """ max_length = 128 if network.version() == 6 else 32 if min_length is None: min_length = network.prefixlen() assert min_length < max_length sql = """ SELECT netaddr FROM prefix WHERE family(netaddr)=%s AND netaddr << %s AND masklen(netaddr) >= %s AND masklen(netaddr) < %s """ args = (network.version(), str(network), min_length, max_length) db_cursor = db.getConnection('default').cursor() db_cursor.execute(sql.strip(), args) db_result = db_cursor.fetchall() return [IP(i[0]) for i in db_result]
def handleTrap(trap, config=None): """ handleTrap is run by snmptrapd every time it receives a trap. Return False to signal trap was discarded, True if trap was accepted. """ db = getConnection('default') # Event variables source = "snmptrapd" target = "eventEngine" eventtypeid = "upsPowerState" # Use the trap-object to access trap-variables and do stuff. for vendor in ONBATTERY.keys(): if trap.snmpTrapOID in ONBATTERY[vendor]: logger.debug ("Got ups on battery trap (%s)" %vendor) # Get time to live try: batterytimeoid, format = BATTERYTIME[vendor] s = Snmp(trap.agent, trap.community) batterytime = s.get(batterytimeoid) except Exception, e: logger.info("Could not get battery time from %s: %s" \ %(trap.agent, e)) batterytime = False else: batterytime = format_batterytime(batterytime, format) logger.debug("batterytime: %s" % batterytime) # Get netboxid from database c = db.cursor() c.execute("SELECT netboxid, sysname FROM netbox WHERE ip = %s", (trap.agent,)) if not c.rowcount > 0: logger.error("Could not find netbox in database, no event \ will be posted") return False netboxid, sysname = c.fetchone() state = 's' # Create event-object, fill it and post event. e = Event(source=source, target=target, netboxid=netboxid, eventtypeid=eventtypeid, state=state) e['alerttype'] = "upsOnBatteryPower" e['batterytime'] = batterytime e['sysname'] = sysname # Post event try: e.post() except Exception, e: logger.error(e) return False return True
def verify_subsystem(): """Verify that subsystem exists, if not insert it into database""" db = getConnection('default') c = db.cursor() sql = """INSERT INTO subsystem (SELECT 'snmptrapd', '' WHERE NOT EXISTS (SELECT * FROM subsystem WHERE name = 'snmptrapd'))""" c.execute(sql) db.commit()
def verifySubsystem (): """Verify that subsystem exists, if not insert it into database""" db = getConnection('default') c = db.cursor() sql = """INSERT INTO subsystem (SELECT 'snmptrapd', '' WHERE NOT EXISTS (SELECT * FROM subsystem WHERE name = 'snmptrapd'))""" c.execute(sql) db.commit()
def test_public_namespace_should_be_empty(): cursor = getConnection('default').cursor() cursor.execute("""SELECT relname FROM pg_class c JOIN pg_namespace n ON (c.relnamespace=n.oid) WHERE nspname='public' ORDER BY nspname""") names = [n for n, in cursor.fetchall()] assert len(names) == 0, ("Objects have been defined in the public " "namespace: " + ".".join(names))
def find_corresponding_netbox(ipaddr): """Find a netboxid corresponding to the given ip address""" cursor = getConnection('default').cursor() try: query = "SELECT netboxid FROM netbox WHERE ip = %s" cursor.execute(query, (ipaddr, )) row = cursor.fetchone() if row: return row[0] except Exception: _logger.exception("Unexpected error when querying database") finally: _logger.debug("Query was: %s", cursor.query)
def delete_old_messages(config): """Delete old messages from db, according to config settings.""" _logger.info("Deleting old messages from db") conn = db.getConnection('logger', 'logger') cursor = conn.cursor() for priority in range(0, 8): if config.get("deletepriority", str(priority)): days = config.getint("deletepriority", str(priority)) cursor.execute( "DELETE FROM log_message WHERE newpriority=%s " "AND time < now() - interval %s", (priority, '%d days' % days)) conn.commit()
def delete_old_messages(config): """Delete old messages from db, according to config settings.""" logger.info("Deleting old messages from db") connection = db.getConnection('logger','logger') cursor = connection.cursor() for priority in range(0, 8): if config.get("deletepriority", str(priority)): days = config.getint("deletepriority", str(priority)) cursor.execute("DELETE FROM log_message WHERE newpriority=%s " "AND time < now() - interval %s", (priority, '%d days' % days)) connection.commit()
def _createMetaMap(family): sql = """SELECT prefixid, nettype, netaddr FROM prefix LEFT JOIN vlan USING (vlanid) WHERE family(netaddr) = %s""" % family cursor = db.getConnection('default', 'manage').cursor() cursor.execute(sql) rows = cursor.fetchall() result = {} for row in rows: result[IP(row[2])] = { "prefixid": row[0], "nettype": row[1], } return result
def dictFromNavDB(): """Build dict from nav DB - key: (device, port) value: description.""" sqlSelect = "SELECT netbox.sysname, interface.ifname, interface.ifalias " sqlFrom = "FROM netbox JOIN interface USING (netboxid)" query = sqlSelect + sqlFrom cursor = getConnection('default').cursor() cursor.execute(query) navDict = {} row = cursor.fetchone() while row is not None: key = (row[0].replace("/", "_").replace(".", "_"), row[1].replace("/", "_").replace(".", "_")) navDict[key] = row[2] row = cursor.fetchone() return navDict
def _lookup_agent(self): """Attempts to look up the corresponding netbox of this trap""" conn = getConnection('snmptrapd') cur = conn.cursor() cur.execute( "SELECT netboxid, sysname, roomid FROM netbox WHERE ip = %s", (self.agent, ), ) if cur.rowcount < 1: _logger.warning( "Unable to match trap agent %s to a NAV-monitored device", self.agent) return None return AgentNetbox(*cur.fetchone())
def _createIpv4MetaMap(cls): sql = """SELECT prefixid, active_ip_cnt, max_ip_cnt, nettype, netaddr FROM prefix LEFT OUTER JOIN prefix_active_ip_cnt USING(prefixid) LEFT OUTER JOIN prefix_max_ip_cnt USING(prefixid) LEFT OUTER JOIN vlan USING(vlanid) WHERE family(netaddr)=4""" cursor = db.getConnection('default', 'manage').cursor() cursor.execute(sql) rows = cursor.fetchall() result = {} for row in rows: tupple = {} tupple["prefixid"] = row[0] tupple["active_ip_cnt"] = row[1] tupple["max_ip_cnt"] = row[2] tupple["nettype"] = row[3] result[IP(row[4])] = tupple return result
def trapHandler(trap): """Handle a trap""" traplogger.info(trap.trapText()) connection = getConnection('default') for mod in handlermodules: logger.debug("Giving trap to %s" %str(mod)) try: accepted = mod.handleTrap(trap, config=config) logger.debug ("Module %s %s trap", mod.__name__, accepted and 'accepted' or 'ignored',) except Exception, why: logger.exception("Error when handling trap with %s: %s" %(mod.__name__, why)) # Assuming that the handler used the same connection as this # function, we rollback any uncommitted changes. This is to # avoid idling in transactions. connection.rollback()
def main(): if (len(sys.argv) <= 2): print "Not enough arguments (%d), <match spec> <up|down>" % ( len(sys.argv),) sys.exit(0) connection = db.getConnection('getDeviceData','manage') cursor = connection.cursor() netboxes = [] device_dupes = set() sysnames = [] for spec in sys.argv[1:-1]: sql = """SELECT module.deviceid,netboxid,moduleid,sysname,name FROM netbox JOIN module USING (netboxid) WHERE ip IS NOT NULL AND sysname ILIKE %s AND name ILIKE %s""" box, module = spec.split(":") cursor.execute(sql, (box, module)) for (deviceid, netboxid, moduleid, sysname, modulename) in cursor.fetchall(): if not deviceid in device_dupes: netboxes.append((deviceid, netboxid, moduleid)) sysnames.append((sysname, modulename)) device_dupes.add(deviceid) if sys.argv[-1].startswith("u"): state = "e" elif sys.argv[-1].startswith("d"): state = "s" else: print "Unknown state: " + sys.argv[-1] sys.exit(0) updown = "up" if (state=="e") else "down" print "Modules going %s: %r" % (updown, sysnames) handler(cursor, netboxes, state) connection.commit()
def __init__(self, report_config): """Does everything in the constructor. queries and returns the values from the database, according to the configuration :param report_config: a ReportConfig object containing the SQL query. """ self.sql = "" self.result = [] self.rowcount = 0 self.sums = {} self.error = "" self.hidden = [] connection = db.getConnection('default') cursor = connection.cursor() self.sql, self.parameters = report_config.make_sql() # Make a dictionary of which columns to summarize self.sums = {sum_key: '' for sum_key in report_config.sum} try: cursor.execute(self.sql, self.parameters or None) self.result = cursor.fetchall() # A list of the column headers. report_config.sql_select = [col.name for col in cursor.description] # Total count of the rows returned. self.rowcount = len(self.result) except psycopg2.ProgrammingError as error: self.error = ("There was an unhandled SQL error! There may be " "something wrong with the definition of the '{}' " "report: {}".format(report_config.title, error)) except psycopg2.DataError as error: self.error = ("Data error! Some of your input data is of an " "invalid type: {}".format(error)) else: self.error = report_config.error
def main(): if (len(sys.argv) <= 2): print("Not enough arguments (%d), <match spec> <up|down>" % ( len(sys.argv),)) sys.exit(0) connection = db.getConnection('getDeviceData','manage') cursor = connection.cursor() netboxes = [] device_dupes = set() sysnames = [] for spec in sys.argv[1:-1]: sql = """SELECT module.deviceid,netboxid,moduleid,sysname,name FROM netbox JOIN module USING (netboxid) WHERE ip IS NOT NULL AND sysname ILIKE %s AND name ILIKE %s""" box, module = spec.split(":") cursor.execute(sql, (box, module)) for (deviceid, netboxid, moduleid, sysname, modulename) in cursor.fetchall(): if not deviceid in device_dupes: netboxes.append((deviceid, netboxid, moduleid)) sysnames.append((sysname, modulename)) device_dupes.add(deviceid) if sys.argv[-1].startswith("u"): state = "e" elif sys.argv[-1].startswith("d"): state = "s" else: print("Unknown state: " + sys.argv[-1]) sys.exit(0) updown = "up" if (state=="e") else "down" print("Modules going %s: %r" % (updown, sysnames)) handler(cursor, netboxes, state) connection.commit()
def _createIpv6MetaMap(cls): """At the time of writing, neither prefix_active_ip_cnt nor prefix_max_ip_cnt contain/calculates the correct values for IPv6. Once this has been fixed, this function needs to be changed.""" sql = """SELECT prefixid, active_ip_cnt, nettype, netaddr FROM prefix LEFT OUTER JOIN prefix_active_ip_cnt USING(prefixid) LEFT OUTER JOIN vlan USING(vlanid) WHERE family(netaddr)=6""" cursor = db.getConnection('default', 'manage').cursor() cursor.execute(sql) rows = cursor.fetchall() result = {} for row in rows: tupple = {} tupple['prefixid'] = row[0] tupple['active_ip_cnt'] = row[1] tupple['nettype'] = row[2] result[IP(row[3])] = tupple return result
def handleTrap(trap, config=None): """ This function is called from snmptrapd """ conn = getConnection('default') cur = conn.cursor() cur.execute("SELECT netboxid, sysname, roomid FROM netbox WHERE ip = %s", (trap.agent,)) if cur.rowcount < 1: logger.error("Could not find trapagent %s in database." %trap.agent) return False netboxid, sysname, roomid = cur.fetchone() oid = trap.snmpTrapOID for handler_class in WeatherGoose1, WeatherGoose2: if handler_class.can_handle(oid): handler = handler_class(trap, netboxid, sysname, roomid) return handler.post_event() return False
def handleTrap(trap, config=None): """ This function is called from snmptrapd """ conn = getConnection('default') cur = conn.cursor() cur.execute("SELECT netboxid, sysname, roomid FROM netbox WHERE ip = %s", (trap.agent, )) if cur.rowcount < 1: logger.error("Could not find trapagent %s in database.", trap.agent) return False netboxid, sysname, roomid = cur.fetchone() oid = trap.snmpTrapOID for handler_class in HANDLER_CLASSES: if handler_class.can_handle(oid): handler = handler_class(trap, netboxid, sysname, roomid) return handler.post_event() return False
def __init__(self, report_config): """Does everything in the constructor. queries and returns the values from the database, according to the configuration :param report_config: a ReportConfig object containing the SQL query. """ self.sql = "" self.result = [] self.rowcount = 0 self.sums = {} self.error = "" self.hidden = [] connection = db.getConnection('default') database = connection.cursor() self.sql = report_config.make_sql() ## Make a dictionary of which columns to summarize self.sums = dict([(sum_key, '') for sum_key in report_config.sum]) try: database.execute(self.sql) self.result = database.fetchall() # A list of the column headers. col_head = [] for col in range(0, len(database.description)): col_head.append(database.description[col][0]) report_config.sql_select = col_head ## Total count of the rows returned. self.rowcount = len(self.result) except psycopg2.ProgrammingError as error: #raise ProblemExistBetweenKeyboardAndChairException self.error = ("Configuration error! The report generator is not " "able to do such things. " + str(error))
def trapHandler(trap): """Handle a trap""" traplogger.info(trap.trapText()) connection = getConnection('default') for mod in handlermodules: logger.debug("Giving trap to %s" % str(mod)) try: accepted = mod.handleTrap(trap, config=config) logger.debug( "Module %s %s trap", mod.__name__, accepted and 'accepted' or 'ignored', ) except Exception, why: logger.exception("Error when handling trap with %s: %s" % (mod.__name__, why)) # Assuming that the handler used the same connection as this # function, we rollback any uncommitted changes. This is to # avoid idling in transactions. connection.rollback()
def __init__(self, report_config): """Does everything in the constructor. queries and returns the values from the database, according to the configuration :param report_config: a ReportConfig object containing the SQL query. """ self.sql = "" self.result = [] self.rowcount = 0 self.sums = {} self.error = "" self.hidden = [] connection = db.getConnection('default') cursor = connection.cursor() self.sql, self.parameters = report_config.make_sql() # Make a dictionary of which columns to summarize self.sums = {sum_key: '' for sum_key in report_config.sum} try: cursor.execute(self.sql, self.parameters or None) self.result = cursor.fetchall() # A list of the column headers. report_config.sql_select = [col.name for col in cursor.description] # Total count of the rows returned. self.rowcount = len(self.result) except psycopg2.ProgrammingError as error: #raise ProblemExistBetweenKeyboardAndChairException self.error = ("Configuration error! The report generator is not " "able to do such things. " + str(error)) else: self.error = report_config.error
def get_interface_details(netboxid, ifindex): """Get interfaceid, deviceid, modulename, ifname, ifalias for interface""" idquery = """SELECT interfaceid, module.deviceid, module.name AS modulename, interface.ifname, interface.ifalias FROM netbox JOIN interface USING (netboxid) LEFT JOIN module USING (moduleid) WHERE netbox.netboxid=%s AND ifindex = %s""" _logger.debug(idquery) cursor = getConnection('default').cursor() try: cursor.execute(idquery, (netboxid, ifindex)) except nav.db.driver.ProgrammingError: _logger.exception("Unexpected error when querying database") else: if cursor.rowcount > 0: return cursor.fetchone() else: _logger.debug('Could not find ifindex %s on %s', ifindex, netboxid) return (None, None, None, None, None)
# # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. You should have received a copy of the GNU General Public License # along with NAV. If not, see <http://www.gnu.org/licenses/>. # "Script to simulate snmpAgentState events from ipdevpoll" import os import nav import sys from nav import db from nav.event import Event import re connection = db.getConnection('default') database = connection.cursor() def handler(nblist, state): for deviceid, netboxid in nblist: e = Event('ipdevpoll', 'eventEngine', deviceid, netboxid, eventtypeid='snmpAgentState', state=state, severity=100) e['alerttype'] = 'snmpAgentDown' if state == 's' else 'snmpAgentUp' e.post() if (len(sys.argv) <= 2): print "Not enough arguments (%d), <match spec> <up|down>" % len(sys.argv) sys.exit(0)
def main(): # Verify that subsystem exists, if not insert it into database verify_subsystem() # Initialize and read startupconfig global config config = ConfigParser.ConfigParser() config.read(configfile) # Create parser and define options opts = parse_args() # When binding to a port < 1024 we need to be root minport = min(port for addr, port in opts.address) if minport < 1024: if os.geteuid() != 0: print("Must be root to bind to ports < 1024, exiting") sys.exit(-1) # Check if already running try: daemon.justme(pidfile) except daemon.DaemonError as why: print(why) sys.exit(-1) # Create SNMP agent object server = agent.TrapListener(*opts.address) server.open() # We have bound to a port and can safely drop privileges runninguser = config.get('snmptrapd', 'user') try: if os.geteuid() == 0: daemon.switchuser(runninguser) except daemon.DaemonError as why: print(why) server.close() sys.exit(-1) global handlermodules nav.logs.init_generic_logging(stderr=True, read_config=True) logger.debug("using %r as SNMP backend", agent.BACKEND) # Load handlermodules try: logger.debug('Trying to load handlermodules') handlermodules = load_handler_modules( config.get('snmptrapd', 'handlermodules').split(',')) except ModuleLoadError as why: logger.error("Could not load handlermodules %s" % why) sys.exit(1) addresses_text = ", ".join( address_to_string(*addr) for addr in opts.address) if opts.daemon: # Daemonize and listen for traps try: logger.debug("Going into daemon mode...") logfile = open(logfile_path, 'a') daemon.daemonize(pidfile, stderr=logfile, stdout=logfile) except daemon.DaemonError as why: logger.error("Could not daemonize: %s", why) server.close() sys.exit(1) # Daemonized; reopen log files nav.logs.reopen_log_files() logger.debug('Daemonization complete; reopened log files.') # Reopen lost db connection # This is a workaround for a double free bug in psycopg 2.0.7 # which is why we don't need to keep the return value getConnection('default') # Reopen log files on SIGHUP logger.debug( 'Adding signal handler for reopening log files on SIGHUP.') signal.signal(signal.SIGHUP, signal_handler) # Exit on SIGTERM signal.signal(signal.SIGTERM, signal_handler) logger.info("Snmptrapd started, listening on %s", addresses_text) try: server.listen(opts.community, trap_handler) except SystemExit: raise except Exception as why: logger.critical("Fatal exception ocurred", exc_info=True) else: # Start listening and exit cleanly if interrupted. try: logger.info("Listening on %s", addresses_text) server.listen(opts.community, trap_handler) except KeyboardInterrupt as why: logger.error("Received keyboardinterrupt, exiting.") server.close()
# You should have received a copy of the GNU General Public License # along with NAV; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # Authors: Kristian Eide <*****@*****.**> # # Script to simulate up/down events from pping # import os import nav import sys from nav import db import re connection = db.getConnection('pping', 'manage') database = connection.cursor() def handler(nblist, state): for nb in nblist: deviceid = nb[0] netboxid = nb[1] msql = "INSERT INTO eventq (source,target,deviceid,netboxid,eventtypeid,state,severity) VALUES ('pping','eventEngine'," + ` deviceid ` + "," + ` netboxid ` + ",'boxState','" + state + "',100)" database.execute(msql) if (len(sys.argv) <= 2): print "Not enough arguments (" + ` len(
# # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. You should have received a copy of the GNU General Public License # along with NAV. If not, see <http://www.gnu.org/licenses/>. # "Script to simulate snmpAgentState events from ipdevpoll" from __future__ import print_function import sys from nav import db from nav.event import Event connection = db.getConnection('default') database = connection.cursor() def handler(nblist, state): for netboxid in nblist: e = Event('ipdevpoll', 'eventEngine', netboxid=netboxid, eventtypeid='snmpAgentState', state=state, severity=100) e['alerttype'] = 'snmpAgentDown' if state == 's' else 'snmpAgentUp' e.post() if (len(sys.argv) <= 2): print("Not enough arguments (%d), <match spec> <up|down>" % len(sys.argv))
# You should have received a copy of the GNU General Public License # along with NAV; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # Authors: Kristian Eide <*****@*****.**> # # Script to simulate up/down events from pping # import os import nav import sys from nav import db import re connection = db.getConnection('pping','manage') database = connection.cursor() def handler(nblist, state): for nb in nblist: deviceid = nb[0] netboxid = nb[1] msql = "INSERT INTO eventq (source,target,deviceid,netboxid,eventtypeid,state,severity) VALUES ('pping','eventEngine',"+`deviceid`+","+`netboxid`+",'boxState','"+state+"',100)" database.execute(msql) if (len(sys.argv) <= 2): print "Not enough arguments ("+`len(sys.argv)`+"), <match spec> <up|down>" sys.exit(0)
# This is an example file, not production code; It will not be linted by # default. Do remove the following line if you fork this module to write your # own: # pylint: disable-all import logging import nav.errors import re from nav.db import getConnection from nav.event import Event # Create logger with modulename here logger = logging.getLogger('nav.snmptrapd.template') # If you need to contact database. global db db = getConnection('default') def handleTrap(trap, config=None): """ handleTrap is run by snmptrapd every time it receives a trap. Return False to signal trap was discarded, True if trap was accepted. """ # Use the trap-object to access trap-variables and do stuff. if trap.genericType in ['LINKUP', 'LINKDOWN']: logger.debug("This is a linkState trap") # config may be fetched like this variable = config.get('template', 'variable')
logger.debug("Going into daemon mode...") daemon.daemonize(pidfile, stderr=nav.logs.get_logfile_from_logger()) except daemon.DaemonError, why: logger.error("Could not daemonize: %s", why) server.close() sys.exit(1) # Daemonized; reopen log files nav.logs.reopen_log_files() logger.debug('Daemonization complete; reopened log files.') # Reopen lost db connection # This is a workaround for a double free bug in psycopg 2.0.7 # which is why we don't need to keep the return value getConnection('default') # Reopen log files on SIGHUP logger.debug('Adding signal handler for reopening log files on SIGHUP.') signal.signal(signal.SIGHUP, signal_handler) # Exit on SIGTERM signal.signal(signal.SIGTERM, signal_handler) logger.info("Snmptrapd started, listening on %s", addresses_text) try: server.listen(opts.community, trapHandler) except SystemExit: raise except Exception, why: logger.critical("Fatal exception ocurred", exc_info=True)
def handleTrap(trap, config=None): """ handleTrap is run by snmptrapd every time it receives a trap. Return False to signal trap was discarded, True if trap was accepted. """ db = getConnection('default') # Event variables source = "snmptrapd" target = "eventEngine" eventtypeid = "upsPowerState" # Use the trap-object to access trap-variables and do stuff. for vendor in ONBATTERY.keys(): if trap.snmpTrapOID in ONBATTERY[vendor]: logger.debug("Got ups on battery trap (%s)", vendor) # Get time to live try: batterytimeoid, format = BATTERYTIME[vendor] s = Snmp(trap.agent, trap.community) batterytime = s.get(batterytimeoid) except Exception as err: logger.info("Could not get battery time from %s: %s", trap.agent, err) batterytime = False else: batterytime = format_batterytime(batterytime, format) logger.debug("batterytime: %s", batterytime) # Get netboxid from database c = db.cursor() c.execute("SELECT netboxid, sysname FROM netbox WHERE ip = %s", (trap.agent, )) if not c.rowcount > 0: logger.error("Could not find netbox in database, no event \ will be posted") return False netboxid, sysname = c.fetchone() state = 's' # Create event-object, fill it and post event. e = Event(source=source, target=target, netboxid=netboxid, eventtypeid=eventtypeid, state=state) e['alerttype'] = "upsOnBatteryPower" e['batterytime'] = batterytime e['sysname'] = sysname # Post event try: e.post() except Exception as e: logger.error(e) return False return True for vendor in OFFBATTERY.keys(): if trap.snmpTrapOID in OFFBATTERY[vendor]: logger.debug("Got ups on utility power trap (%s)", vendor) # Get netboxid from database c = db.cursor() c.execute("SELECT netboxid, sysname FROM netbox WHERE ip = %s", (trap.agent, )) if not c.rowcount > 0: logger.error("Could not find netbox in database, no event \ will be posted") return False netboxid, sysname = c.fetchone() state = 'e' # Create event-object, fill it and post event. e = Event(source=source, target=target, netboxid=netboxid, eventtypeid=eventtypeid, state=state) e['sysname'] = sysname e['alerttype'] = "upsOnUtilityPower" # Post event try: e.post() except Exception as e: logger.error(e) return False return True return False