def DeployConfig_jcs(local_int, ckn, cak, conn_name=None):

    logger.debug('====> In DeployConfig_jcs')

    try:
        if conn_name is None:
            conn_name = id_generator()

        script = "system-check.py"
        change_xml = """<security>
                            <macsec>
                                <connectivity-association>
                                    <name>{0}</name>
                                    <security-mode>static-cak</security-mode>
                                    <pre-shared-key>
                                        <ckn>{1}</ckn>
                                        <cak>{2}</cak>
                                    </pre-shared-key>
                                </connectivity-association>
                                <interfaces>
                                    <name>{3}</name>
                                    <connectivity-association>{0}</connectivity-association>
                                </interfaces>
                            </macsec>
                        </security>""".format(conn_name, ckn, cak, local_int)
        jcs.emit_change(change_xml, "change", "xml")
    except Exception as e:
        jcs.emit_warning(
            'Cannot deploy pre-shared key, skip automatically MACsec deployment'
        )
        jcs.emit_warning('Please see debug logs for detail.')
        quit()

    logger.debug('<==== Out DeployConfig_jcs')
def main():

    root = Junos_Configuration

    message = " - Permission all is assigned to invalid class"

    for element in root.findall("./system/login/class[permissions='all']"):
        jcs.emit_warning("class: " + element.find("name").text + message)
def main():
    # Get configuration root object
    root = Junos_Configuration

    message = "Permission all is assigned to invalid class."

    # Warn about any login classes with the all permission set
    for element in root.findall("./system/login/class[permissions='all']"):
        jcs.emit_warning("class:" + element.find('name').text + " " + message)
Exemple #4
0
def main():
    # Get configuration root object
    root = Junos_Configuration

    # Check for 'lo0' interface existence and firewall configuration
    lo0_interface = root.find("./interfaces/interface[name='lo0']")
    lo0_interface_firewall = lo0_interface.find(
        "./unit[name='0']/family/inet/filter/input")

    # Emit warning if firewall not configured
    if lo0_interface and not (lo0_interface_firewall):
        jcs.emit_warning("no lo0.0 firewall filter is assigned")
def main():
    # Get configuration root object
    root = Junos_Configuration

    # Loop through all logical interfaces
    for element in root.findall("./interfaces/interface/unit"):
        # Missing description
        if element.find('description') == None:
            # Emit warning message to console
            jcs.emit_warning("Interface description is missing: " +
                             element.find('../name').text + " Unit: " +
                             element.find('name').text)
Exemple #6
0
def main():
    # jcs.output => Output the message to CLI
    jcs.output('testing jcs output ')

    # jcs.get_input => Prompt user for input, echoed back to user
    user_input = jcs.get_input(' ')
    # Dump the user entered output
    jcs.output(user_input)

    # jcs.get_secret => Prompt user for input, not echoed back to user
    user_input = jcs.get_secret(' ')
    # Dump the user entered output
    jcs.output(user_input)

    # Run the script with 'cli> op extensions.py detail ' to view progress message
    jcs.progress("Progress message from python op-script")

    # Syslog the message
    jcs.syslog("pfe.alert", "Sample syslog message from python op-script")
    jcs.syslog("161", "Sample syslog message from python op-script")

    # Getting hostname of box (Please note DNS needs to be configured)
    hostname = jcs.hostname("bng-ui-vm-05")
    print hostname

    # SYSCTL information
    osrelease = jcs.sysctl("kern.osrelease", "s")
    slotid = jcs.sysctl("hw.re.slotid", "i")
    print osrelease
    print slotid

    # This is from jcs.printf(...)
    jcs.printf("%s", "JUNOS")

    # Send information to configured trace file using jcs.trace(...)
    jcs.trace("teting jcs trace")

    # Emit warning message to console
    jcs.emit_warning("Warning message from Python op script")

    # Dampening script execution based on return value
    dampen_value = jcs.dampen('TEST', 3, 10)
    print dampen_value

    # Emit error message to console
    jcs.emit_error("Error message from Python op script")
Exemple #7
0
def main():
    # Get configuration root object
    root = Junos_Configuration

    # Check for 'fxp0' existence
    fxp0_interface = root.find("./interfaces/interface[name='fxp0']")

    # Compare attribute value
    if fxp0_interface is not None:
        inherited_re0 = fxp0_interface.find("[@{http://xml.juniper.net/junos/*/junos}group='re0']")
        inherited_re1 = fxp0_interface.find("[@{http://xml.juniper.net/junos/*/junos}group='re1']")

        # Emit warning if 'fxp0' configured and not inheirted from 're' group
        if inherited_re0 is None and inherited_re1 is None:
            jcs.emit_warning("fxp0 configuration is present but not inherited from re group")

    else:
        jcs.emit_warning("fxp0 configuration not present")
def rest_request_post(query):

    logger.debug('====> In rest_request_post')

    response = None

    try:
        headers = {"content-type": "application/json"}
        response = requests.post(url="http://{0}:{1}/QueryCAKCKN".format(
            SERVER_IP, SERVER_PORT),
                                 headers=headers,
                                 data=json.dumps({
                                     "LocalChassisID":
                                     query.LocalChassisID,
                                     "LocalInt":
                                     query.LocalInt,
                                     "LocalHostname":
                                     query.LocalHostname,
                                     "RemoteChassisID":
                                     query.RemoteChassisID,
                                     "RemoteInt":
                                     query.RemoteInt,
                                     "RemoteHostname":
                                     query.RemoteHostname
                                 }))
    except Exception as e:
        jcs.emit_warning(
            'Cannot request data from server, please check sever connectivity with URL: {0}:{1}'
            .format(SERVER_IP, SERVER_PORT))
        jcs.emit_warning('Following AutoMACsec configuration would SKIP!')
        logger.error(str(e))
        quit()

    logger.debug('<==== Out rest_request_post')

    return response
def main():
    root = Junos_Configuration
    if not (root.xpath("./chassis/source-route")):
        jcs.emit_warning("IP source-route processing is not enabled.")
def main():
    jcs.emit_warning("Warning message from Python commit script")
    jcs.emit_error("Error message from Python commit script")
def main():
    dev = Device()
    info = InfoCollector(dev)

    # check if device supports macsec function.
    chassis_hardware = dev.rpc.get_chassis_inventory()
    device_description = chassis_hardware.xpath(".//description")[0].text
    logger.info("device_description is: " + device_description)

    device_name = device_description.split(sep, 1)[0]
    logger.info("device_name is: " + device_name)

    if device_name in device_list:
        logger.info("This device supports macsec function!")
    else:
        logger.info(
            "This device is not supporting MACsec funtion for now. Process abort."
        )
        return

    if device_name in device_list_license:
        logger.info(
            "This device also requests a licnese to be installed for macsec function,start checking required license now..."
        )

        licenses = dev.rpc.get_license_summary_information()

        for ifd in licenses.getiterator("feature-summary"):
            if (ifd.find("name").text.strip() == 'macsec'):
                logger.info("License name: " + ifd.find("name").text.strip())
                logger.info("MACsec license has installed.")
                break
            else:
                print("Searching for required macsec license...")
                logger.info("Searching for required macsec license...")

    #collecting MACsec info
    dictLocalIntConn = info.getMACsec_interface_conn()
    dictConnCKNCAK = info.getMACsec_conn_key()

    #collecting local info
    Local_ChassisID, Local_Hostname = info.get_local_id_hostname()

    #compose query for interface which is half configured.
    for local_int in info.dictLocalIntConn:
        remote_chassisID, remote_int, remote_hostname = info.get_remote_ID_port_by_LLDP(
            local_int)

        query = tuple_Query_CKNCAK(Local_ChassisID, local_int, Local_Hostname,
                                   remote_chassisID, remote_int,
                                   remote_hostname)

        lstQueryCKNCAK.append(query)

    logger.info('Information ready, prepared to query from remote master')

    #Query preshared key from server.
    for query in lstQueryCKNCAK:
        #Get responding ckn & cak
        dict_ServerResponse = json.loads(rest_request_post(query).text)

        logger.info('Got response from remote master')

        #Check existing ckn & cak match or not, if there's any.
        if dictLocalIntConn[query.LocalInt] in dictConnCKNCAK:
            logger.info('pre-shared key comparison')

            #Get current configured preshared key
            cur_CKNCAK = dictConnCKNCAK[dictLocalIntConn[query.LocalInt]]

            if ((dict_ServerResponse['ckn'] != cur_CKNCAK.ckn
                 or dict_ServerResponse['cak'] != Decryptor().juniper_decrypt(
                     cur_CKNCAK.cak)) and dict_ServerResponse['ckn'] != None
                    and dict_ServerResponse['cak'] != None):
                #ckn cak needs to be updated.
                logger.info('pre-shared key needs update')

                jcs.emit_warning(
                    "Get latest pre-shared key from server, update it to interface {0}"
                    .format(query.LocalInt))
                DeployConfig_jcs(query.LocalInt, dict_ServerResponse['ckn'],
                                 dict_ServerResponse['cak'],
                                 dictLocalIntConn[query.LocalInt])

                logger.info('finish pre-shared key update')
            else:
                logger.info('pre-shared key match, skip update.')
                #ckn & cak matched, do not reconfigured.
                pass

        else:
            #There's not exising pre-shared key, deploy it.
            logger.info(
                'pre-shared key not existed, need to deploy a new one.')

            if dict_ServerResponse['ckn'] != None and dict_ServerResponse[
                    'cak'] != None:
                jcs.emit_warning(
                    "Automatically generate pre-shared key and deploy it on interface {0}"
                    .format(query.LocalInt))
                DeployConfig_jcs(query.LocalInt, dict_ServerResponse['ckn'],
                                 dict_ServerResponse['cak'],
                                 dictLocalIntConn[query.LocalInt])
                logger.info('pre-shared key deployed.')
            else:
                #display error msg since there's no existing record in Database.
                #Possible scenario:
                #1. User delete the record and macsec configuration accidentally
                #   -> LLDP is not working. -> Cannot recover from error state.
                #   -> Inform user to delete both side's macsec configuration, and make sure LLDP is up&running, then try again.
                logger.error(
                    'No match record in remote_master\'s database, please delete related records \
                        and make sure LLDP is up and running between devices')
                logger.error(
                    'e.g. junos@MX480> op delete_MACsec_interface.py <Device ChassisID> <Device interface name>'
                )
                jcs.emit_error(
                    "There's not matched pre-shared key in database, please delete both side's macsec configuration and try again."
                )

        # Check if MKA works
        '''
import jcs
jcs.emit_warning("Hello World")
Exemple #13
0
from junos import Junos_Configuration as root
import jcs

if __name__ == "__main__":
    message = "Permission all is assigned to invalid class."
    for element in root.findall("system/login/class[permissions='all']"):
        jcs.emit_warning("class:" + element.findtext('name') + " " + message)