Exemplo n.º 1
0
def main():
    openlog(LOGFILE)

    # Look for the trigger event message.
    #
    # In this case, we have no useful metadata because it's a message from the
    # kernel's TCP stack rather than rpd, so we must use a regular expression
    # to extract the peer IP that is attempting TCP MD5 connection.
    #
    # Note: there is an assumption here that TCP MD5 must be BGP, although no
    # peers will be added unless they match the group's configured source-address allow
    # list.
    msg = Junos_Trigger_Event.xpath(
        '/event-script-input/trigger-event/message')[0].text
    m = re.match(
        "tcp_auth_ok: Packet from (.*):\d+ unexpectedly has (MD5|AUTH) digest",
        msg)
    if m == None:
        logmsg("WARNING: Couldn't find IP address in event input: ignoring")
        exit(0)
    else:
        neighbor = m.group(1)

        # Extract current committed configuration
        with Device() as dev:
            config = dev.rpc.get_config(
                options={'database': 'committed'},
                filter_xml=etree.fromstring(
                    '<configuration><protocols><bgp/></protocols></configuration>'
                ))

            # Check BGP peer with IP address DOES NOT already exist
            if config.xpath(
                ('count(//configuration/protocols/bgp/group/neighbor[name="%s"])'
                 % neighbor)) > 0:
                logmsg("Neighbor %s is already configured: ignoring", neighbor)
                exit(0)

            # For every group configured with an apply-macro { source-address "A.B.C.D/E etc" } stanza...
            # extract the group name and the list of allowed source ranges.
            for group in config.xpath(
                    '//configuration/protocols/bgp/group' +
                    '[apply-macro/name="autopeer" and apply-macro/data/name="source-address"]'
            ):
                groupname = group.findtext("name")
                allowed_src = config.xpath(
                    ('//configuration/protocols/bgp/group[name="%s"]' %
                     groupname) +
                    '/apply-macro[name="autopeer"]/data/value')[0].text.split(
                        " ")

                # Check if the neighbor matches any of the allowed sources,
                # adding him to the group if so, then stopping
                for src in allowed_src:
                    if check_group_acl(src, neighbor) == True:
                        add_peer(dev, groupname, neighbor)
                        break
Exemplo n.º 2
0
def main():
    # Record the facility
    facility = str(Junos_Trigger_Event.xpath('//trigger-event/facility')[0].text)
    # Get the process name
    process_name = str(Junos_Trigger_Event.xpath('//trigger-event/process/name')[0].text)
    # Get PID
    pid = str(Junos_Trigger_Event.xpath('//trigger-event/process/pid')[0].text)
    # Get the syslog message
    message = str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text)

    # Assemble message
    if int(pid) > 0:
        final_message = process_name + "[" + pid + "]: " + message
    else:
        final_message = process_name + ": " + message

    # New Priority
    new_priority = facility + ".notice"

    # Now re-syslog it with the new facility
    jcs.syslog(new_priority, final_message)
def main():
    fo = open("/var/tmp/event_input_extract.txt", "w+")
    fo.write("Event script input: \n")
    fo.write("******************* \n")
    fo.write("Junos context info: \n")
    fo.write("******************* \n")
    fo.write(str(Junos_Context))

    fo.write("\n\nTriggering event details: \n")
    fo.write("*************************\n")
    fo.write("id: " +
             str(Junos_Trigger_Event.xpath('//trigger-event/id')[0].text) +
             "\n")
    fo.write("type: " +
             str(Junos_Trigger_Event.xpath('//trigger-event/type')[0].text) +
             "\n")
    fo.write("generation-time: " + str(
        Junos_Trigger_Event.xpath('//trigger-event/generation-time')[0].text) +
             "\n")
    fo.write("process-name: " + str(
        Junos_Trigger_Event.xpath('//trigger-event/process/name')[0].text) +
             "\n")
    fo.write(
        "process-pid: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/process/pid')[0].text) +
        "\n")
    fo.write(
        "hostname: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/hostname')[0].text) +
        "\n")
    fo.write(
        "facility: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/facility')[0].text) +
        "\n")
    fo.write(
        "severity: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/severity')[0].text) +
        "\n")
    fo.close()
def main():
    i = 1
    event_message = str(
        Junos_Trigger_Event.xpath('//trigger-event/message')[0].text)
    event_message_log = event_message.replace(" ", "_")
    facility = str(
        Junos_Trigger_Event.xpath('//trigger-event/facility')[0].text)
    '''BW Community prefix is configurable but, to be safe, let's stick to a-zA-Z_ range '''
    if re.match('^[a-zA-Z_]{2,}$', args.bgp_community_prefix):
        bw_community_prefix = args.bgp_community_prefix
    else:
        log(i, 'ERROR', 'BW Community prefix is not valid. Using default.')
        bw_community_prefix = 'bw_community_'
    ''' Sanity check on ae interface name '''
    ae_ifd = re.search('Bandwidth.*> (ae[0-9]+) index', event_message)
    if ae_ifd:
        ae_ifd = ae_ifd.group(1)
        ''' Go with a syslog event regardless if debugging is enabled '''
        jcs.syslog(
            "172",
            os.path.basename(__file__) + ": Executed for AE" + str(ae_ifd))
        #log(i, 'DEBUG', "AE_IFD:"+str(ae_ifd))
        log(i, 'DEBUG',
            "Connecting to device and retrieving speed of " + str(ae_ifd))
    else:
        log(i, 'ERROR', "COULD NOT RETRIEVE AE NAME FROM EVENT")
        sys.exit()
    ''' Connect to device '''
    dev = Device(gather_facts=False).open(normalize=True)
    with Config(dev, mode='dynamic') as cu:

        log(i, 'DEBUG', "Connection successful")
        ''' Sleep 2 seconds and wait for RPD to update AE speed '''
        log(i, 'DEBUG', "Sleeping 2 seconds")
        sleep(1)
        ''' Let's retrieve AE speed and description '''
        log(i, 'DEBUG', "Retrieving aggregate " + str(ae_ifd) + " information")
        agg_show = dev.rpc.get_interface_information(interface_name=ae_ifd)
        agg_speed = agg_show.xpath('string(//physical-interface/speed)')
        agg_speed_bps = agg_speed.replace("Unspecified", "0")
        agg_speed_bps = agg_speed_bps.replace("Gbps", "")
        ''' Per https://www.juniper.net/documentation/en_US/junos/topics/example/bgp-multipath-unequal.html, bw community
            second number represents value in bytes per second in the [0-4294967295] (34Gbps) range. '''
        if agg_speed_bps > 0:
            agg_speed_bps = int(agg_speed_bps) * 1000000 / 8
        log(i, 'DEBUG',
            "Interface " + str(ae_ifd) + " speed is " + str(agg_speed_bps))
        ''' If AE.0 (Design of this script checks unit 0 description) description does not match specific string, I'm not interested in this LAG '''
        agg_description = agg_show.xpath(
            "physical-interface/logical-interface[name='" + str(ae_ifd) +
            ".0']/description")
        if len(agg_description) == 0:
            log(
                i, 'ERROR', "Interface " + str(ae_ifd) +
                " has no description under unit 0. Trying the IFD.")
            agg_description = agg_show.xpath("physical-interface[name='" +
                                             str(ae_ifd) + "']/description")
            if len(agg_description) == 0:
                log(
                    i, 'ERROR', "Interface " + str(ae_ifd) +
                    " IFD has no description either. I'm confused, so I will exit to avoid problems."
                )
                return
            agg_description = agg_description[0].text
        elif len(agg_description) == 1:
            agg_description = agg_description[0].text
            log(
                i, 'DEBUG', "Interface " + str(ae_ifd) +
                " IFD has description:" + str(agg_description))
        else:
            sys.exit()
        ''' Check if IFD/IFL.0 description matches requirements '''
        regex = re.compile('%s' % str(args.ae_intf_regex))
        if not regex.match(agg_description):
            log(
                i, 'DEBUG',
                "Not interested in AE >" + str(ae_ifd) + "< Description >" +
                agg_description + "< Regex>" + args.ae_intf_regex + "<")
            return
        log(
            i, 'DEBUG', "Aggregate Speed:" + str(agg_speed_bps) +
            " and aggregate description:" + str(agg_description) +
            ". I'm interested in it.")
        ''' Retrieve AS number '''
        ASN = dev.rpc.get_config(filter_xml=etree.XML(
            '<configuration><routing-options><autonomous-system/></routing-options></configuration>'
        ),
                                 options={
                                     'inherit': 'inherit',
                                     'database': 'committed'
                                 })
        ASN = ASN.xpath(
            'string(//routing-options/autonomous-system/as-number)')
        log(i, 'DEBUG', "Our AS is:" + str(ASN))
        log(i, 'DEBUG', "All information retrieved. Building configuration.")
        ''' Build BW Community config '''
        config_xml = """
            <configuration>
                <policy-options>
                    <community replace="replace">
                        <name>{0}</name>
                        <members>bandwidth:{1}:{2}</members>
                    </community>
                </policy-options>
            </configuration>
        """.format(
            str(bw_community_prefix) + str(ae_ifd), ASN, str(agg_speed_bps))
        ''' If Commit DB Lock fails, wait configurable number of seconds '''
        log(
            i, 'DEBUG',
            "Entering wait loop. Wait time to commit (if db is locked) is:" +
            str(args.wait))

        while i <= int(args.wait):
            ''' Loading configuration '''
            log(i, 'DEBUG', "Loading configuration changes")
            try:
                cu.load(config_xml, format="xml", merge=False)
            except ConfigLoadError as err:
                log(i, 'DEBUG', "Building configuration")
                '''try:
                    dev.cu.unlock()
                except UnlockError:
                    log(i, 'ERROR', "Unable to unlock configuration")
                dev.close()'''
                return
            ''' Commit configuration '''
            log(i, 'DEBUG', "Committing the configuration")
            try:
                cu.commit()
                return
            except CommitError as err:
                ''' This prins the commit error to script output captured in destination directory present in configuration (TMP) '''
                print(format(err))
                log(
                    i, 'ERROR',
                    "Unable to commit configuration. Unlocking the configuration"
                )
                try:
                    dev.cu.unlock()
                except UnlockError:
                    log(i, 'ERROR', "Unable to unlock configuration")
                dev.close()
                return
        '''dev.close()'''
Exemplo n.º 5
0
def main():
    sLogFileName = "/var/tmp/DHCP_DNS.log"
    sDebugLevel = logging.DEBUG
    # Logging Levels:
    #    debug          logging.DEBUG
    #    info           logging.INFO
    #    warning        logging.WARNING
    #    error          logging.ERROR
    #    critical       logging.CRITICAL

    logging.basicConfig(filename=sLogFileName, level=sDebugLevel)

    logging.debug("****NEW EVENT************")
    logging.debug("Junos context info: " + str(Junos_Context))
    logging.debug("Triggering event details:")
    logging.debug("id: " +
                  str(Junos_Trigger_Event.xpath('//trigger-event/id')[0].text))
    logging.debug(
        "type: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/type')[0].text))
    logging.debug("generation-time: " + str(
        Junos_Trigger_Event.xpath('//trigger-event/generation-time')[0].text))
    logging.debug(
        "process-name: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/process/name')[0].text))
    logging.debug(
        "process-pid: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/process/pid')[0].text))
    logging.debug(
        "hostname: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/hostname')[0].text))
    logging.debug(
        "facility: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/facility')[0].text))
    logging.debug(
        "severity: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/severity')[0].text))
    logging.debug(
        "message: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text))

    sEventMessage = (str(
        Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(
            ",")[0].split(":")[0]).replace(" ", "")
    sClientMac = (str(
        Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(
            ",")[2]).split(" ")[2].replace(" ", "")
    sClientIP = (str(
        Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(
            ",")[3]).split(" ")[2].replace(" ", "")
    if ("DH_SVC_V4_SERVER_RCV_RELEASE"
            or "DH_SVC_V4_SERVER_LEASE_TIMEOUT") in sEventMessage:
        sClientIP = sClientIP[:len(sClientIP) - 1]

    logging.info("****CLIENT INFO**********")
    logging.info("EVENT: " + sEventMessage)
    logging.info("MAC: " + sClientMac)
    logging.info("IP: " + sClientIP)
    logging.info("****CLIENT INFO**********")

    fnDNS(sEventMessage, sClientIP)

    logging.debug("****END EVENT ***********")
Exemplo n.º 6
0
def main():
    sLogFileName = "/var/tmp/DHCP_DNS.log"
    sDebugLevel = logging.DEBUG
    FORMAT = "[%(asctime)s:%(levelname)s:%(funcName)s ] %(message)s"
    # Logging Levels:
    #    debug          logging.DEBUG
    #    info           logging.INFO
    #    warning        logging.WARNING
    #    error          logging.ERROR
    #    critical       logging.CRITICAL

    logging.basicConfig(format=FORMAT,
                        datefmt='%d-%b-%y %H:%M:%S',
                        filename=sLogFileName,
                        level=sDebugLevel)

    logging.debug("[main] ****NEW EVENT************")
    logging.debug("[main] Junos context info: " + str(Junos_Context))
    logging.debug("[main] Triggering event details:")
    logging.debug("[main] id: " +
                  str(Junos_Trigger_Event.xpath('//trigger-event/id')[0].text))
    logging.debug(
        "[main] type: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/type')[0].text))
    logging.debug("[main] generation-time: " + str(
        Junos_Trigger_Event.xpath('//trigger-event/generation-time')[0].text))
    logging.debug(
        "[main] process-name: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/process/name')[0].text))
    logging.debug(
        "[main] process-pid: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/process/pid')[0].text))
    logging.debug(
        "[main] hostname: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/hostname')[0].text))
    logging.debug(
        "[main] facility: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/facility')[0].text))
    logging.debug(
        "[main] severity: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/severity')[0].text))
    logging.debug(
        "[main] message: " +
        str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text))

    sEventMessage = (str(
        Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(
            ",")[0].split(":")[0]).replace(" ", "")
    sClientMac = (str(
        Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(
            ",")[2]).split(" ")[2].replace(" ", "")
    sClientIP = (str(
        Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(
            ",")[3]).split(" ")[2].replace(" ", "")
    if ("DH_SVC_V4_SERVER_RCV_RELEASE"
            or "DH_SVC_V4_SERVER_LEASE_TIMEOUT") in sEventMessage:
        sClientIP = sClientIP[:len(sClientIP) - 1]

    logging.info("[main] ****CLIENT INFO**********")
    logging.info("[main] EVENT: " + sEventMessage)
    logging.info("[main] MAC: " + sClientMac)
    logging.info("[main] IP: " + sClientIP)
    logging.info("[main] ****CLIENT INFO**********")

    fnDNS(sEventMessage, sClientIP, sClientMac)

    logging.debug("[main] ****END EVENT ***********")
Exemplo n.º 7
0
def main():
    debugging = True

    if debugging:
        fo = open("/var/tmp/DHCP_DNS_DEBUG.log", "a")
    else:
        fo = open("/var/log/DHCP_DNS.log", "a")

    if debugging:
        fo.write("Junos context info: \n")
        fo.write("*************************\n")
        fo.write(str(Junos_Context) + "\n")
        fo.write("*************************\n")

    if debugging:
        fo.write("*************************\n")
        fo.write("Triggering event details: \n")
        fo.write("*************************\n")
        fo.write("id: " + str(Junos_Trigger_Event.xpath('//trigger-event/id')[0].text) + "\n")
        fo.write("type: " + str(Junos_Trigger_Event.xpath('//trigger-event/type')[0].text) + "\n")
        fo.write("generation-time: " + str(Junos_Trigger_Event.xpath('//trigger-event/generation-time')[0].text))
        fo.write("process-name: " + str(Junos_Trigger_Event.xpath('//trigger-event/process/name')[0].text) + "\n")
        fo.write("process-pid: " + str(Junos_Trigger_Event.xpath('//trigger-event/process/pid')[0].text) + "\n")
        fo.write("hostname: " + str(Junos_Trigger_Event.xpath('//trigger-event/hostname')[0].text) + "\n")
        fo.write("facility: " + str(Junos_Trigger_Event.xpath('//trigger-event/facility')[0].text) + "\n")
        fo.write("severity: " + str(Junos_Trigger_Event.xpath('//trigger-event/severity')[0].text) + "\n")
        fo.write("message: " + str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text) + "\n")

    event_message = (str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(",")[0].split(":")[0]).replace(" ","")
    client_mac = (str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(",")[2]).split(" ")[2].replace(" ","")
    client_ip = (str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(",")[3]).split(" ")[2].replace(" ","")

    fo.write("*************************\n")
    fo.write("CLIENT INFO: \n")
    fo.write("*************************\n")
    fo.write("EVENT: " + event_message + "\n")
    fo.write("MAC: " + client_mac + "\n")
    fo.write("IP: " + client_ip + "\n")

    if debugging:
        fo.write("*************************\n")
        fo.write("DHCP PROCESS: \n")
        fo.write("*************************\n")
    if "DH_SVC_V4_SERVER_RCV_RENEW" in event_message:
        fo.write("-----DHCP RENEW----------\n")
    if "DH_SVC_V4_SERVER_RCV_RELEASE" in event_message:
        fo.write("-----DHCP RELEASE--------\n")
    if "DH_SVC_V4_SERVER_GET_BOUND" in event_message:
        fo.write("-----DHCP BOUND----------\n")

    if debugging:
        fo.write("\n")

    fo.close()
Exemplo n.º 8
0
def main():
    bDEBUGGING = True


    if bDEBUGGING:
        fnDEBUG(bDEBUGGING, "Junos context info: \n")
        fnDEBUG(bDEBUGGING, "*************************\n")
        fnDEBUG(bDEBUGGING, str(Junos_Context) + "\n")
        fnDEBUG(bDEBUGGING, "*************************\n")

    if bDEBUGGING:
        fnDEBUG(bDEBUGGING, "*************************\n")
        fnDEBUG(bDEBUGGING, "Triggering event details: \n")
        fnDEBUG(bDEBUGGING, "*************************\n")
        fnDEBUG(bDEBUGGING, "id: " + str(Junos_Trigger_Event.xpath('//trigger-event/id')[0].text) + "\n")
        fnDEBUG(bDEBUGGING, "type: " + str(Junos_Trigger_Event.xpath('//trigger-event/type')[0].text) + "\n")
        fnDEBUG(bDEBUGGING, "generation-time: " + str(Junos_Trigger_Event.xpath('//trigger-event/generation-time')[0].text))
        fnDEBUG(bDEBUGGING, "process-name: " + str(Junos_Trigger_Event.xpath('//trigger-event/process/name')[0].text) + "\n")
        fnDEBUG(bDEBUGGING, "process-pid: " + str(Junos_Trigger_Event.xpath('//trigger-event/process/pid')[0].text) + "\n")
        fnDEBUG(bDEBUGGING, "hostname: " + str(Junos_Trigger_Event.xpath('//trigger-event/hostname')[0].text) + "\n")
        fnDEBUG(bDEBUGGING, "facility: " + str(Junos_Trigger_Event.xpath('//trigger-event/facility')[0].text) + "\n")
        fnDEBUG(bDEBUGGING, "severity: " + str(Junos_Trigger_Event.xpath('//trigger-event/severity')[0].text) + "\n")
        fnDEBUG(bDEBUGGING, "message: " + str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text) + "\n")

    sEventMessage = (str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(",")[0].split(":")[0]).replace(" ","")
    sClientMac = (str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(",")[2]).split(" ")[2].replace(" ","")
    sClientIP = (str(Junos_Trigger_Event.xpath('//trigger-event/message')[0].text).split(",")[3]).split(" ")[2].replace(" ","")

    fnDEBUG(sOutput = "*************************\n")
    fnDEBUG(sOutput = "CLIENT INFO: \n")
    fnDEBUG(sOutput = "*************************\n")
    fnDEBUG(sOutput = "EVENT: " + sEventMessage + "\n")
    fnDEBUG(sOutput = "MAC: " + sClientMac + "\n")
    fnDEBUG(sOutput = "IP: " + sClientIP + "\n")

    if bDEBUGGING:
        fnDEBUG(bDEBUGGING, "*************************\n")
        fnDEBUG(bDEBUGGING, "DHCP PROCESS: \n")
        fnDEBUG(bDEBUGGING, "*************************\n")
    fnDNS(sEventMessage, sClientIP)
    if bDEBUGGING:
        fnDEBUG(bDEBUGGING, "\n")