def main(): global conf args = parse_args() # Todo: fail if config file is not found conf = configparser.ConfigParser() conf.read(find_configfile(CONFIG_FILE)) # Must do this after config, so logfile can be configurable if args.test: init_logging('-') else: init_logging(LOG_FILE) add_mailin_subsystem() plugins = conf.get('main', 'plugins').split() plugins = load_plugins(plugins) if args.init: _logger.info('Initialization done. Exiting.') return read_and_process_input(plugins, test=args.test) _logger.info('Done')
def report_detentions(profile, detentions): """For all ip's that are detained, group by contactinfo and send mail""" LOGGER.debug("Trying to report detentions") emails = find_contact_addresses(detentions) try: mailfile = find_configfile( join("arnold", "mailtemplates", profile.mailfile)) message_template = open(mailfile).read() except IOError as error: LOGGER.error(error) return for email, iplist in emails.items(): LOGGER.info("Sending mail to %s", email) fromaddr = 'noreply' toaddr = email reason = profile.name subject = "Computers detained because of %s" % profile.justification msg = message_template msg = re.sub(r'\$reason', reason, msg) msg = re.sub(r'\$list', "\n".join([" ".join(x) for x in iplist]), msg) try: nav.arnold.sendmail(fromaddr, toaddr, subject, msg) except Exception as error: LOGGER.error(error) continue
def ipdevpoll_test_config(): print("placing temporary ipdevpoll config") configfile = find_configfile("ipdevpoll.conf") tmpfile = configfile + '.bak' os.rename(configfile, tmpfile) with open(configfile, "w") as config_handle: config_handle.write( """ [snmp] # we don't need timeout tests to take forever: timeout=0.1 [plugins] snmpcheck= crash=nav.ipdevpoll.plugins.debugging.Crash error=nav.ipdevpoll.plugins.debugging.Error fail=nav.ipdevpoll.plugins.debugging.Fail sleep=nav.ipdevpoll.plugins.debugging.Sleep noop=nav.ipdevpoll.plugins.debugging.Noop """ ) config.ipdevpoll_conf = config.IpdevpollConfig() # test load from scratch plugins.import_plugins() yield configfile print("restoring ipdevpoll config") os.remove(configfile) os.rename(tmpfile, configfile)
def load_from_file(cls, filename: str = CONFIG_FILE) -> 'SeverityRules': """Instantiates a SeverityRules object from rule definitions in a YAML file""" full_path = config.find_configfile(filename) if not full_path: _logger.debug("could not find severity config file %s", filename) return None else: _logger.debug("loading severity rules from %s", full_path) with open(full_path) as conf: return cls.load(conf)
def raise_if_detainment_not_allowed(interface, trunk_ok=False): """Raises an exception if this interface should not be detained""" netbox = interface.netbox config = get_config(find_configfile(CONFIGFILE)) allowtypes = [x.strip() for x in str(config.get('arnold', 'allowtypes')).split(',')] if netbox.category.id not in allowtypes: _logger.info("Not allowed to detain on %s", netbox.category.id) raise WrongCatidError(netbox.category) if not trunk_ok and interface.trunk: _logger.info("Cannot detain on a trunk") raise BlockonTrunkError
def test_plugin_loader_reading_in_modules_from_config_file(): configfile = find_configfile("snmptrapd.conf") config = configparser.ConfigParser() config.read(configfile) list_from_config = config.get('snmptrapd', 'handlermodules').split(',') assert type(list_from_config) == list if len(list_from_config) <= 0: pytest.skip("Requires at least one plugin in snmptrapd.conf to run" " this integration test with loading plugins") loaded_modules = load_handler_modules(list_from_config) assert len(list_from_config) == len(loaded_modules)
def eventengine_test_config(): print("placing temporary eventengine config") configfile = find_configfile("eventengine.conf") tmpfile = configfile + ".bak" os.rename(configfile, tmpfile) with open(configfile, "w") as config: config.write(""" [timeouts] boxDown.warning = 1s boxDown.alert = 2s """) yield configfile print("restoring eventengine config") os.remove(configfile) os.rename(tmpfile, configfile)
def main(): # Figure out what to do (options, _args) = parse_options() # Process setup config = ConfigParser() config.read(find_configfile('logger.conf')) nav.logs.init_stderr_logging() if options.delete: # get rid of old records delete_old_messages(config) sys.exit(0) else: logengine(config, options)
def pping_test_config(): print("placing temporary pping config") configfile = find_configfile("pping.conf") tmpfile = configfile + '.bak' os.rename(configfile, tmpfile) with open(configfile, "w") as config: config.write(""" user = {user} checkinterval = 2 packetsize = 64 timeout = 1 nrping = 2 delay = 2 """.format(user=getpass.getuser())) yield configfile print("restoring ping config") os.remove(configfile) os.rename(tmpfile, configfile)
def check_non_block(ip): """Checks if the ip is in the nonblocklist.""" nonblockdict = parse_nonblock_file(find_configfile(NONBLOCKFILE)) # We have the result of the nonblock.cfg-file in the dict # nonblockdict. This dict contains 3 things: # 1 - Specific ip-addresses # 2 - Ip-ranges (129.241.xxx.xxx/xx) # 3 - Ip lists (129.241.xxx.xxx-xxx) # Specific ip-addresses if ip in nonblockdict['ip']: LOGGER.info('Computer in nonblock list, skipping') raise InExceptionListError # Ip-ranges for ip_range in nonblockdict['range']: if ip in IP(ip_range): raise InExceptionListError
def smsd_test_config(): print("placing temporary smsd config") configfile = find_configfile("smsd.conf") tmpfile = configfile + '.bak' os.rename(configfile, tmpfile) with open(configfile, "w") as config: config.write(""" [main] mailwarnlevel: CRITICAL [dispatcher] dispatcher1: UninettMailDispatcher [UninettMailDispatcher] mailaddr: root@localhost """) yield configfile print("restoring smsd config") os.remove(configfile) os.rename(tmpfile, configfile)
def ipdevpoll_test_config(): print("placing temporary ipdevpoll config") configfile = find_configfile("ipdevpoll.conf") tmpfile = configfile + '.bak' os.rename(configfile, tmpfile) with open(configfile, "w") as config_handle: config_handle.write(""" [plugins] snmpcheck= crash=nav.ipdevpoll.plugins.debugging.Crash error=nav.ipdevpoll.plugins.debugging.Error fail=nav.ipdevpoll.plugins.debugging.Fail sleep=nav.ipdevpoll.plugins.debugging.Sleep noop=nav.ipdevpoll.plugins.debugging.Noop """) config.ipdevpoll_conf.read_all() plugins.import_plugins() yield configfile print("restoring ipdevpoll config") os.remove(configfile) os.rename(tmpfile, configfile)
def exceptions_response(request): """ Handler for exception-mode. """ if not request.is_ajax(): return HttpResponseRedirect( reverse(index) + '?' + request.GET.urlencode()) account = get_account(request) if not account: return HttpResponseRedirect('/') config = ConfigParser() config.read(find_configfile('logger.conf')) options = config.options("priorityexceptions") excepts = [] context = {} for option in options: newpriority = config.get("priorityexceptions", option) excepts.append((option, newpriority)) context['exceptions'] = excepts context['exceptions_mode'] = True return render(request, 'syslogger/frag-exceptions.html', context)
def get_configuration(): global _config if _config is None: _config = read_configuration( find_configfile(os.path.join('geomap', 'config.py'))) return _config
import sys import configparser import os.path from django.http import HttpResponse import nav.logs from nav.config import find_configfile _logger = logging.getLogger(__name__) default_app_config = 'nav.web.apps.NAVWebAppConfig' webfrontConfig = configparser.ConfigParser() _configfile = find_configfile(os.path.join('webfront', 'webfront.conf')) if _configfile: webfrontConfig.read(_configfile) def refresh_session(request): """Forces a refresh of the session by setting the modified flag""" request.session.modified = True _logger.debug('refresh_session: refreshed') return HttpResponse() def loginit(): """Initialize a logging setup for the NAV web interface. All logging is directed to stderr, which should end up in Apache's
# License along with NAV. If not, see <http://www.gnu.org/licenses/>. # """NAV related logging functionality.""" import sys import os import logging from itertools import chain import configparser from nav.config import find_configfile, NAV_CONFIG DEFAULT_LOG_FORMATTER = logging.Formatter('%(asctime)s [%(levelname)s] ' '[%(name)s] %(message)s') LOGGING_CONF_VAR = 'NAV_LOGGING_CONF' LOGGING_CONF_FILE_DEFAULT = find_configfile('logging.conf') or '' _logger = logging.getLogger(__name__) def set_log_config(): """Set log levels and custom log files""" set_log_levels() _set_custom_log_file() def set_log_levels(): """ Read the logging config file and set up log levels for the different loggers. """
def test_should_be_valid(self): full_path = find_configfile(CONFIG_FILE) assert full_path, f"Could not find severity rule config file {CONFIG_FILE}" assert SeverityRules.load_from_file(full_path)
"""NAV web common package.""" import os from django.db.models import Count from django.http import Http404 from nav.config import find_configfile from nav.models.profiles import AccountDashboard WELCOME_ANONYMOUS_PATH = find_configfile( os.path.join("webfront", "welcome-anonymous.txt")) WELCOME_REGISTERED_PATH = find_configfile( os.path.join("webfront", "welcome-registered.txt")) NAV_LINKS_PATH = find_configfile(os.path.join("webfront", "nav-links.conf")) DEFAULT_WIDGET_COLUMNS = 2 def get_widget_columns(account): """Get the preference for widget columns""" return int( account.preferences.get(account.PREFERENCE_KEY_WIDGET_COLUMNS, DEFAULT_WIDGET_COLUMNS)) def find_dashboard(account, dashboard_id=None): """Find a dashboard for this account Either find a specific one or the default one. If none of those exist we find the one with the most widgets. """
"""Util functions for the PortAdmin""" from __future__ import unicode_literals import re import configparser import logging from operator import attrgetter from os.path import join from django.template import loader from nav.config import find_configfile from nav.django.utils import is_admin from nav.portadmin.snmputils import SNMPFactory, FantasyVlan from nav.enterprise.ids import VENDOR_ID_CISCOSYSTEMS CONFIGFILE = find_configfile(join("portadmin", "portadmin.conf")) or '' _logger = logging.getLogger("nav.web.portadmin") def get_and_populate_livedata(netbox, interfaces): """Fetch live data from netbox""" handler = SNMPFactory.get_instance(netbox) live_ifaliases = create_dict_from_tuplelist(handler.get_all_if_alias()) live_vlans = create_dict_from_tuplelist(handler.get_all_vlans()) live_operstatus = dict(handler.get_netbox_oper_status()) live_adminstatus = dict(handler.get_netbox_admin_status()) update_interfaces_with_snmpdata(interfaces, live_ifaliases, live_vlans, live_operstatus, live_adminstatus) return handler
from django.utils.six import PY2, iteritems, text_type from nav.models.manage import Prefix from nav.report.IPtree import get_max_leaf, build_tree from nav.report.generator import Generator, ReportList from nav.report.matrixIPv4 import MatrixIPv4 from nav.report.matrixIPv6 import MatrixIPv6 from nav.report.metaIP import MetaIP from nav.config import find_configfile from nav.web.navlets import add_navlet _logger = logging.getLogger(__name__) IpGroup = namedtuple('IpGroup', 'private ipv4 ipv6') CONFIG_FILE_PACKAGE = find_configfile(os.path.join("report", "report.conf")) CONFIG_FILE_LOCAL = find_configfile(os.path.join("report", "report.local.conf")) FRONT_FILE = find_configfile(os.path.join("report", "front.html")) DEFAULT_PAGE_SIZE = 25 PAGE_SIZES = [25, 50, 100, 500, 1000] def index(request): """Report front page""" context = { 'title': 'Report - Index', 'navpath': [('Home', '/'), ('Report', False)], 'heading': 'Report Index' }
import signal import subprocess import sys import time import re import yaml from django.utils import six from nav.config import open_configfile, find_configfile, NAV_CONFIG from nav.errors import GeneralException from nav import buildconf INFOHEAD = '## info:' DAEMON_CONFIG = 'daemons.yml' CRON_DIR = find_configfile('cron.d') def get_info_from_content(content): """Extracts and returns service information from an iterable""" for line in content: if not line.startswith('#'): break elif line.startswith(INFOHEAD): return line[len(INFOHEAD):].strip() class Service(object): """Represents a NAV service in general, and should never be instantiated.""" def __init__(self, filename):
These tests simply enumerate all known reports and ensure that the dbresult is error free. This only ensures that the SQL can be run, no further verification is performed. """ from __future__ import unicode_literals import pytest from django.http import QueryDict from django.urls import reverse from nav import db from nav.report.generator import ReportList, Generator from nav.config import find_configfile config_file = find_configfile('report/report.conf') config_file_local = find_configfile('report/report.local.conf') def report_list(): result = ReportList(config_file) return [report[0] for report in result.reports] @pytest.mark.parametrize("report_name", report_list()) def test_report(report_name): #uri = 'http://example.com/report/%s/' % report_name uri = QueryDict('').copy() db.closeConnections() # Ensure clean connection for each test generator = Generator()
import os from operator import attrgetter from django.conf import settings from nav.config import find_configfile from nav.django.auth import get_sudoer from nav.django.utils import get_account, is_admin from nav.web.message import Messages from nav.web.webfront.utils import tool_list, quick_read, split_tools from nav.models.profiles import NavbarLink from nav.buildconf import VERSION from nav.metrics import CONFIG CONTACT_INFORMATION_PATH = find_configfile( os.path.join("webfront", "contact-information.txt")) def debug(_request): """Returns context variables helpful for debugging. Same as django.templates.context_processors.debug, just without the check against INTERNAL_IPS.""" context_extras = {} if settings.DEBUG: context_extras['debug'] = True from django.db import connection context_extras['sql_queries'] = connection.queries return context_extras