Exemplo n.º 1
0
def init_logging(filename):
    if filename == '-':
        logs.init_stderr_logging()
    else:
        if conf.has_option('main', 'logfile'):
            filename = conf.get('main', 'logfile')
        logs.init_generic_logging(logfile=filename, stderr=False)
Exemplo n.º 2
0
def main(args):
    """Main controller"""

    init_generic_logging(
        logfile=LOG_FILE,
        stderr=False,
        read_config=True,
    )

    if args.listblocktypes:
        print_detention_profiles()
        return

    LOGGER.info('Starting automatic detentions based on %s', args.profile.name)
    addresses = get_addresses_to_detain(args)

    detentions = []  # List of successfully blocked ip-addresses
    for address, comment in addresses:
        try:
            detentions.append(detain(address, args.profile, comment))
        except GeneralException as error:
            LOGGER.error(error)
            continue

    if args.profile.mailfile and detentions:
        report_detentions(args.profile, detentions)
Exemplo n.º 3
0
def main():
    """Main program"""
    init_generic_logging(
        logfile=LOGFILE,
        stderr=True,
        formatter=logging.Formatter(LOGFORMAT),
        read_config=False,
        stderr_level=logging.ERROR
        if sys.stderr.isatty() else logging.CRITICAL,
    )
    stderr = logging.getLogger('')
    django.setup()

    opts = parse_args()

    if opts.verify:
        LOGGER.info("-v option used, setting log level to DEBUG")
        stderr.setLevel(logging.DEBUG)
        LOGGER.setLevel(logging.DEBUG)

    sysnames = []
    if opts.hostname:
        sysnames.append(opts.hostname.strip())
    if opts.hostsfile:
        sysnames.extend(read_hostsfile(opts.hostsfile))

    LOGGER.debug('Start checking PSUs and FANs')
    check_psus_and_fans(get_psus_and_fans(sysnames), dryrun=opts.dryrun)
Exemplo n.º 4
0
def main():
    """Main controller"""
    init_generic_logging(
        logfile=nav.buildconf.localstatedir + "/log/arnold/autoenable.log",
        stderr=False,
        read_config=True,
    )
    LOGGER.info("Starting autoenable")

    candidates = Identity.objects.filter(
        autoenable__lte=datetime.now(), status__in=['disabled', 'quarantined'])

    if len(candidates) <= 0:
        LOGGER.info("No ports ready for opening.")
        sys.exit(0)

    # For each port that is blocked, try to enable the port.
    for candidate in candidates:
        try:
            open_port(candidate, getpass.getuser(),
                      eventcomment="Opened automatically by autoenable")
            interface = candidate.interface
            netbox = interface.netbox
            LOGGER.info("Opening %s %s:%s for %s",
                        netbox.sysname, interface.module, interface.baseport,
                        candidate.mac)
        except GeneralException as why:
            LOGGER.error(why)
            continue
Exemplo n.º 5
0
def main(options):
    """Main controller"""

    init_generic_logging(
        logfile=nav.buildconf.localstatedir + "/log/arnold/start_arnold.log",
        stderr=False,
        read_config=True,
    )

    if options.listblocktypes:
        print_detention_profiles()
        return

    profile = verify_options(options)
    if not profile:
        return

    LOGGER.info('Starting automatic detentions based on %s' % profile.name)
    addresses = get_addresses_to_detain(options)

    detentions = []  # List of successfully blocked ip-addresses
    for address, comment in addresses:
        try:
            detentions.append(detain(address, profile, comment))
        except GeneralException, error:
            LOGGER.error(error)
            continue
Exemplo n.º 6
0
def main():
    """Main thresholdmon program"""
    parser = make_option_parser()
    (_options, _args) = parser.parse_args()

    init_generic_logging(
        logfile=LOGFILE_PATH,
        stderr=False,
        stdout=True,
        read_config=True,
    )
    django.setup()
    scan()
Exemplo n.º 7
0
def main():
    """Main program"""
    init_generic_logging(
        logfile=LOGFILE,
        stderr=True,
        formatter=logging.Formatter(LOGFORMAT),
        read_config=False,
        stderr_level=logging.ERROR
        if sys.stderr.isatty() else logging.CRITICAL,
    )
    stderr = logging.getLogger('')
    django.setup()

    parser = OptionParser()
    parser.add_option(
        "-d",
        "--dry-run",
        action="store_true",
        dest="dryrun",
        help="Dry run.  No changes will be made and no events posted")
    parser.add_option(
        "-f",
        "--file",
        dest="hostsfile",
        help="A file with hostnames to check. Must be one FQDN per line")
    parser.add_option("-n",
                      "--netbox",
                      dest="hostname",
                      help="Check only this hostname.  Must be a FQDN")
    parser.add_option("-v",
                      "--verify",
                      action="store_true",
                      dest="verify",
                      help="Print (lots of) debug-information to stderr")
    opts, _args = parser.parse_args()

    if opts.verify:
        LOGGER.info("-v option used, setting log level to DEBUG")
        stderr.setLevel(logging.DEBUG)
        LOGGER.setLevel(logging.DEBUG)

    sysnames = []
    if opts.hostname:
        sysnames.append(opts.hostname.strip())
    if opts.hostsfile:
        sysnames.extend(read_hostsfile(opts.hostsfile))

    LOGGER.debug('Start checking PSUs and FANs')
    check_psus_and_fans(get_psus_and_fans(sysnames), dryrun=opts.dryrun)
Exemplo n.º 8
0
 def __init__(self, **kwargs):
     signal.signal(signal.SIGHUP, self.signalhandler)
     signal.signal(signal.SIGTERM, self.signalhandler)
     self.conf = config.serviceconf()
     init_generic_logging(stderr=True, read_config=True)
     self._deamon = kwargs.get("fork", 1)
     self._isrunning = 1
     self._checkers = []
     self._looptime = int(self.conf.get("checkinterval", 60))
     LOGGER.debug("Setting checkinterval=%i", self._looptime)
     self.db = db.db()
     LOGGER.debug("Reading database config")
     LOGGER.debug("Setting up runqueue")
     self._runqueue = RunQueue.RunQueue(controller=self)
     self.dirty = 1
Exemplo n.º 9
0
def main():
    """Good old main..."""
    before = time.time()
    fmt = logging.Formatter(LOG_FORMAT)
    init_generic_logging(
        logfile=LOG_FILE, stderr=False, formatter=fmt, read_config=True
    )
    _logger = logging.getLogger('')

    _logger.debug('-' * 60)  # Visual separation line
    try:
        check_devices_on_maintenance()
    except Exception:
        _logger.exception("An unhandled exception occurred:")
    _logger.debug('Finished in %.3fs' % (time.time() - before))
    _logger.debug('-' * 60)  # Visual separation line
Exemplo n.º 10
0
 def __init__(self, **kwargs):
     signal.signal(signal.SIGHUP, self.signalhandler)
     signal.signal(signal.SIGTERM, self.signalhandler)
     self.config = config.pingconf()
     init_generic_logging(stderr=True, read_config=True)
     self._isrunning = 1
     self._looptime = int(self.config.get("checkinterval", 60))
     LOGGER.info("Setting checkinterval=%i", self._looptime)
     self.db = db.db()
     sock = kwargs.get("socket", None)
     self.pinger = megaping.MegaPing(sock)
     self._nrping = int(self.config.get("nrping", 3))
     # To keep status...
     self.netboxmap = {}  # hash netboxid -> netbox
     self.down = []  # list of netboxids down
     self.replies = {}  # hash netboxid -> circbuf
     self.ipToNetboxid = {}
Exemplo n.º 11
0
    def __init__(self, foreground=False):
        if not foreground:
            signal.signal(signal.SIGHUP, self.signalhandler)
        signal.signal(signal.SIGTERM, self.signalhandler)
        signal.signal(signal.SIGINT, self.signalhandler)

        self.conf = config.serviceconf()
        init_generic_logging(stderr=True, read_config=True)
        self._isrunning = 1
        self._checkers = []
        self._looptime = int(self.conf.get("checkinterval", 60))
        _logger.debug("Setting checkinterval=%i", self._looptime)
        self.db = db.db()
        _logger.debug("Reading database config")
        _logger.debug("Setting up runqueue")
        self._runqueue = RunQueue.RunQueue(controller=self)
        self.dirty = 1
Exemplo n.º 12
0
def main():
    """Main controller"""
    init_generic_logging(logfile=join(localstatedir, 'log', LOGFILE),
                         stderr=False)
    config = NetbiosTrackerConfig()

    start = time.time()
    _logger.info('=== Starting netbiostracker ===')

    addresses = tracker.get_addresses_to_scan(config.get_exceptions())
    scanresult = tracker.scan(addresses)
    parsed_results = tracker.parse(scanresult, config.get_encoding())
    tracker.update_database(parsed_results)

    _logger.info('Scanned %d addresses, got %d results in %.2f seconds',
                 len(addresses), len(parsed_results), time.time() - start)
    _logger.info('Netbiostracker done')
Exemplo n.º 13
0
def main():
    """Main program"""
    init_generic_logging(
        logfile=LOGFILE,
        stderr=True,
        read_config=True,
    )

    opts = parse_args()

    sysnames = []
    if opts.hostname:
        sysnames.append(opts.hostname.strip())
    if opts.hostsfile:
        sysnames.extend(read_hostsfile(opts.hostsfile))

    LOGGER.debug('Start checking PSUs and FANs')
    check_psus_and_fans(get_psus_and_fans(sysnames), dryrun=opts.dryrun)
Exemplo n.º 14
0
    def __init__(self, socket=None, foreground=False):
        if not foreground:
            signal.signal(signal.SIGHUP, self.signalhandler)
        signal.signal(signal.SIGTERM, self.signalhandler)
        signal.signal(signal.SIGINT, self.signalhandler)

        self.config = config.pingconf()
        init_generic_logging(stderr=True, read_config=True)
        self._isrunning = 1
        self._looptime = int(self.config.get("checkinterval", 60))
        _logger.info("Setting checkinterval=%i", self._looptime)
        self.db = db.db()
        self.pinger = megaping.MegaPing(socket)
        self._nrping = int(self.config.get("nrping", 3))
        # To keep status...
        self.netboxmap = {}  # hash netboxid -> netbox
        self.down = []  # list of netboxids down
        self.replies = {}  # hash netboxid -> circbuf
        self.ip_to_netboxid = {}
Exemplo n.º 15
0
def main():
    """Good old main..."""
    before = time.clock()
    log_file = os.path.join(nav.buildconf.localstatedir,
                            'log', 'maintengine.log')
    fmt = logging.Formatter(LOG_FORMAT)
    init_generic_logging(
        logfile=log_file,
        stderr=False,
        formatter=fmt,
        read_config=True,
    )
    logger = logging.getLogger('')

    logger.debug('------------------------------------------------------------')
    try:
        check_devices_on_maintenance()
    except Exception:
        logger.exception("An unhandled exception occurred:")
    logger.debug('Finished in %.3fs' % (time.clock() - before))
    logger.debug('------------------------------------------------------------')
Exemplo n.º 16
0
Arquivo: t1000.py Projeto: a31amit/nav
def main():
    """Main controller"""
    init_generic_logging(
        logfile=nav.buildconf.localstatedir + "/log/arnold/t1000.log",
        stderr=False,
        read_config=True,
    )
    LOGGER.info("Starting t1000")
    django.setup()

    # Fetch all mac-addresses that we have detained, check if they are
    # active somewhere else. As NAV collects arp and cam data periodically,
    # we need to give one hour slack to ensure data is correct.

    identities = Identity.objects.filter(
        last_changed__lte=datetime.now() - timedelta(hours=1),
        status__in=['disabled', 'quarantined'])

    if len(identities) <= 0:
        LOGGER.info("No detained ports in database where lastchanged > 1 "
                    "hour.")
        sys.exit(0)

    for identity in identities:
        LOGGER.info("%s is %s, checking for activity",
                    identity.mac, identity.status)
        try:
            candidate = find_computer_info(identity.mac)
        except NoDatabaseInformationError as error:
            LOGGER.info(error)
            continue

        # If this mac-address is active behind another port, block it.
        if candidate.endtime > datetime.now():
            if candidate.interface == identity.interface:
                LOGGER.info('Active on detained interface, will not pursue')
            else:
                pursue(identity, candidate)
        else:
            LOGGER.info("%s is not active.", candidate.mac)
Exemplo n.º 17
0
Arquivo: detector.py Projeto: hmpf/nav
def main():
    """Program entry point"""
    parser = make_option_parser()
    options = parser.parse_args()

    init_generic_logging(
        logfile=LOG_FILE,
        stderr=options.stderr,
        stdout=True,
        read_config=True,
    )
    if options.l2 or options.vlan:
        # protect against multiple invocations of long-running jobs
        verify_singleton()
    if options.l2:
        do_layer2_detection()
    if options.vlan:
        if options.include_vlans:
            vlans = [int(v) for v in options.include_vlans]
        else:
            vlans = []
        do_vlan_detection(vlans)
        delete_unused_prefixes()
        delete_unused_vlans()
Exemplo n.º 18
0
def main(days=None):
    """Controller"""
    exit_if_already_running()
    init_generic_logging(logfile=LOGFILE, stderr=False)
    run(days)
Exemplo n.º 19
0
def main(args):
    """Send all reports"""
    init_generic_logging(logfile=LOGFILE, stderr=False)
    send_reports(args.period)