def main(): parser = argparse.ArgumentParser( description='Pings remote host and prints the rtt details.') parser.add_argument('-host', required=True, help='IP address of remote host') parser.add_argument('-count', required=True, help='Number of attempts') args = parser.parse_args() args.host = args.host args.count = args.count dev = Device() dev.open() try: result = dev.rpc.ping(host=args.host, count=args.count) message = "Rtt details for host " + result.findtext("target-host").lstrip().rstrip() + " at time " + str(Junos_Context['localtime']) \ + " Minimum = " + result.findtext("probe-results-summary/rtt-minimum").lstrip().rstrip() \ + " Maximum = " + result.findtext("probe-results-summary/rtt-maximum").lstrip().rstrip() \ + " Average = " + result.findtext("probe-results-summary/rtt-average").lstrip().rstrip() except: message = "Ping to host " + str(args.host) + " at time " + str( Junos_Context['localtime']) + " failed" jcs.syslog("external.info", message) # dump the output to a file fo = open("/var/tmp/sample.txt", "w+") fo.write(message) fo.close() dev.close()
def main(): root = Junos_Configuration for element in root.xpath("./snmp/community"): if element.find("authorization") is None or \ element.find("authorization").text != 'read-write': jcs.syslog( "172", "SNMP community does not have read-write access: " + element.find('name').text)
def log(i, log_type, log_line): if args.debug == "enable": jcs.syslog( "172", os.path.basename(__file__) + ": iteration " + str(i) + ":" + log_type + ": " + log_line) else: return
def main(): data = Junos_Configuration y = 0 for elem in data.xpath(".//interface[name='ae0']//input/filter-name"): x = int(str(elem.text).split('g')[0]) y += x if y == 15: jcs.syslog("172", "Works")
def disable_interface(interface_name): try: with Device() as dev: with Config(dev, 'exclusive') as cu: cu.load('set interfaces {0} disable'.format(interface_name)) cu.commit() except Exception as inst: jcs.syslog('external.warn', "{0}: Unable to disable interface.".format(interface_name)) jcs.syslog('external.warn', "{0}.".format(inst))
def main(): snmp_action = jcs.get_snmp_action() snmp_oid = jcs.get_snmp_oid() jcs.syslog("8", "snmp_action = ", snmp_action, " snmp_oid = ", snmp_oid) if snmp_action != 'get': return if not snmp_oid.startswith(BASE_OID): return index = int(snmp_oid[len(BASE_OID) + 1:]) if index not in SCRIPT_XPATH: return with Device() as dev: conf = dev.rpc.get_config() count_scripts = len(conf.xpath(SCRIPT_XPATH[index])) jcs.emit_snmp_attributes(snmp_oid, "Integer32", str(count_scripts))
def snmp_get_instance_value(leaf, instance): if instance is None: return None message = "Inside snmp_get_value " + "instance: " + str(instance) #jcs.syslog("external.info", message) lwaftr = lwaftr_statistics_dict[instance] #jcs.syslog("external.info", lwaftr) if lwaftr is None: jcs.syslog("external.info", "no entry") return None if (leaf == LWAFTR_INSTANCE_TABLE_NAME): return lwaftr.lwaftrName; if (leaf == LWAFTR_INSTANCE_TABLE_BREATHS): return str(lwaftr.lwaftrbreaths) return None
def snmp_get_value(leaf, instance, protocol): if instance is None: return None message = "Inside snmp_get_value " + "instance: " + str(instance) + " protocol: " + str(protocol) #jcs.syslog("external.info", message) lwaftr = lwaftr_statistics_dict[instance] #jcs.syslog("external.info", lwaftr) if lwaftr is None: jcs.syslog("external.info", "no entry") return None if (leaf == 3): return lwaftr.lwaftrName; if (protocol == SNMP_V4_STATISTICS): if (leaf == LWAFTR_HCINOCTETS): #jcs.syslog("external.info", "leaf=4") value = lwaftr.lwaftrV4HCInOctets elif (leaf == LWAFTR_HCINPACKETS): value = lwaftr.lwaftrV4HCInPkts elif (leaf == LWAFTR_HCOUTOCTETS): value = lwaftr.lwaftrV4HCOutOctets elif (leaf == LWAFTR_HCOUTPACKETS): value = lwaftr.lwaftrV4HCOutPkts elif (leaf == LWAFTR_HCOCTETDROPS): value = lwaftr.lwaftrV4HCOctetDrops elif (leaf == LWAFTR_HCOPACKETDROPS): value = lwaftr.lwaftrV4HCPktDrops else: return return str(value) elif (protocol == SNMP_V6_STATISTICS): if (leaf == LWAFTR_HCINOCTETS): value = lwaftr.lwaftrV6HCInOctets elif (leaf == LWAFTR_HCINPACKETS): value = lwaftr.lwaftrV6HCInPkts elif (leaf == LWAFTR_HCOUTOCTETS): value = lwaftr.lwaftrV6HCOutOctets elif (leaf == LWAFTR_HCOUTPACKETS): value = lwaftr.lwaftrV6HCOutPkts elif (leaf == LWAFTR_HCOCTETDROPS): value = lwaftr.lwaftrV6HCOctetDrops elif (leaf == LWAFTR_HCOPACKETDROPS): value = lwaftr.lwaftrV6HCPktDrops else: return return str(value) return None
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")
def main(): snmp_action = jcs.get_snmp_action() snmp_oid = jcs.get_snmp_oid() jcs.syslog("8", "snmp_action = ", snmp_action, " snmp_oid = ", snmp_oid) if snmp_action == 'get': if snmp_oid == '.1.3.6.1.4.1.2636.13.61.1.9.1.1': jcs.emit_snmp_attributes(snmp_oid, "Integer32", "10") elif snmp_oid == '.1.3.6.1.4.1.2636.13.61.1.9.1.1.1': jcs.emit_snmp_attributes(snmp_oid, "Integer32", "211") elif snmp_action == 'get-next': if snmp_oid == '.1.3.6.1.4.1.2636.13.61.1.9.1.1': jcs.emit_snmp_attributes(".1.3.6.1.4.1.2636.13.61.1.9.1.1.1", "Integer32", "211") elif snmp_oid == '.1.3.6.1.4.1.2636.13.61.1.9.1.1.1': jcs.emit_snmp_attributes(".1.3.6.1.4.1.2636.13.61.1.9.1.1.2", "Integer32", "429")
def main(): jdev = Device() # Opens a connection jdev.open() # Get show system storage rsp = jdev.rpc.get_system_storage() # rsp = jdev.cli("show system storage", format="xml") # Retrieve the '/var' percent percent = rsp.xpath(".//filesystem[normalize-space(mounted-on)='/var']/used-percent")[0].text strip_percent = int(percent.strip()) if strip_percent > 75: syslog_message = "Warning: /var utilization is at " + str(strip_percent) + "%" jcs.syslog("external.warning", syslog_message) # Close the connection jdev.close()
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(): data = Junos_Configuration allocated_bandwidth = 0 for i in data.xpath(".//interface/unit[name='0']/description"): interco_bandiwdth = int(str(i.text).split('g')[0]) for i in data.xpath(".//interface[name='ae0']//input/filter-name"): unit_bandwidth = int(str(i.text).split('g')[0]) allocated_bandwidth += unit_bandwidth remaining_capacity = (interco_bandiwdth * 4.5) - allocated_bandwidth if allocated_bandwidth >= interco_bandiwdth * 4.5: jcs.syslog( "2", "CAPACITY CRITICAL: VLAN Attachment Bandwidth excedded the Interconnect capacity by 450% Contract violated" ) elif allocated_bandwidth >= interco_bandiwdth * 2.25: jcs.syslog( "2", "CAPACITY CRITICAL: VLAN Attachment Bandwidth reached 250% - Plan an upgrade!" ) else: jcs.syslog( "6", "CAPACITY NOTICE: Contractual Interconnect capacity remaining " + str(remaining_capacity) + "gbps")
def compare_lldp_info(): expected_topology = { 'fxp0': { 'Chassis_ID': '50:c7:09:a3:c5:9d', 'System_Name': 'gw.pod3.cce' }, 'xe-1/1/0': { 'Chassis_ID': '50:c7:09:bb:64:dc', 'System_Name': 'spine2.pod3.cce' }, 'xe-1/1/1': { 'Chassis_ID': '50:c7:09:c5:8b:0c', 'System_Name': 'spine1.pod3.cce' }, 'xe-1/1/2': { 'Chassis_ID': 'abc123', 'System_Name': 'unknown host' } } try: with Device() as dev: lldp = LLDPNeighborTable(dev) lldp.get() for item in lldp: if item['local_int'] in expected_topology.keys() \ and item['remote_chassis_id'] == expected_topology[item['local_int']['Chassis_ID']] \ and item['remote_sysname'] == expected_topology[item['local_int']['System_Name']]: jcs.syslog( 'external.info', "{0}: Expected interface found.".format( item['local_int'])) else: jcs.syslog( 'external.warn', "{0}: Cabling mismatch detected.".format( item['local_int'])) jcs.syslog( 'external.warn', "{0}: Disabling interface.".format(item['local_int'])) disable_interface(item['local_int']) except Exception as inst: jcs.syslog('external.warn', "{0}: Unable to verify LLDP information.".format(inst))
def main(): # Get script name for logging script = os.path.basename(__file__) # Setup argument parsing for dynamic config parser = argparse.ArgumentParser() parser.add_argument('-interface', required=True) args = parser.parse_args() try: # create device object dev = Device(gather_facts=False) # open connection to device dev.open() # create configuration object cu = Config(dev) # Send syslog from facility external with severity info to say main IF is down jcs.syslog("external.warn", "{0}: Cette interface est tombee".format(script)) # Set configuration data # Stripping out the single quote from argument (this may be a bug that's fixed) conf = "delete interfaces {0} disable".format( args.interface.strip('\'')) try: # Get configuration lock cu.lock() # Load configuration cu.load(conf, format='set') # Commit configuration cu.commit(comment='Event script {0}'.format(script)) # Unlock config cu.unlock() # Catch configuration lock error except LockError: jcs.syslog("external.error", "{0}: Unable to lock configuration".format(script)) dev.close() return # Catch configuration load error # Requires PyEZ >= 1.1.0 # except ConfigLoadError as err: # jcs.syslog("external.error", # "{0}: Unable to load configuration - {1},{2},{3}".format(script, # err.errs['severity'], # err.errs['bad_element'], # err.errs['message'])) # dev.close() # return # Catch configuration commit error # More details are available in PyEZ >= 1.1.0 except CommitError: jcs.syslog("external.error", "{0}: Unable to commit configuration".format(script)) pass # Catch unlock error except UnlockError: jcs.syslog("external.error", "{0}: Unable to commit configuration".format(script)) dev.close() return dev.close() except Exception as err: jcs.syslog("external.error", "{0}: Uncaught excpetion - {1}".format(script, err))
def main(): usage = """ This script adds or replaces a static route for the given prefix to the given network interface via Amazon EC2 CreateRoute op aws-replace-route.py interface <interface> prefix <ipv4-cidr-prefix/mask> \ [role <iam-role-name>] [debug <level>] Default AWS IAM role is 'changeRoute' Set debug level to 1 to get debugging information along the way Set debug level to 2 to also get the complete VPC routing table on the interface """ parser = argparse.ArgumentParser(description='replace-route') parser.add_argument("-interface", help="local interface", type=str) parser.add_argument("-prefix", help="IPv4 prefix", type=str) parser.add_argument("-role", help="IAM role name", type=str) parser.add_argument("-debug", help="debug level", type=int) args = parser.parse_args() if type(args.interface) is str and type(args.prefix) is str: interface = args.interface ipv4_prefix = args.prefix else: print usage exit() if type(args.debug) is int: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) iam_role = 'changeRoute' if type(args.role) is str: iam_role = args.role try: eths = check_output(['/sbin/ifconfig', interface]) except: print "interface " + interface + " doesn't exist" exit() m = re.search('i802\s+(.+)', eths) if not m: # maybe we are running in linux m = re.search('HWaddr\s+([0-9:a-f]+)', eths) else: print "can't find mac address for interface " + interface exit() macaddr = m.group(1) # normalize address for ec2 lookup to work macaddr = ":".join([i.zfill(2) for i in macaddr.split(":")]).lower() logging.debug(interface + " has mac " + macaddr) cloud_init_url = "http://169.254.169.254/latest/meta-data/" url = cloud_init_url + "network/interfaces/macs/" + macaddr + "/interface-id" interface_id = urllib2.urlopen(url).read() url = cloud_init_url + "network/interfaces/macs/" + macaddr + "/vpc-id" vpc_id = urllib2.urlopen(url).read() url = cloud_init_url + "placement/availability-zone" region = urllib2.urlopen(url).read() region = region[:-1] logging.debug("vpc_id=" + vpc_id + " interface_id=" + interface_id + " region=" + region) # read temporary credentials via cloud-init. Requires pre-defined IAM role # changeRoute url = cloud_init_url + "iam/security-credentials/" + iam_role cred = urllib2.urlopen(url).read() data = json.loads(cred) access_key = data['AccessKeyId'] secret_key = data['SecretAccessKey'] authorization_token = data['Token'] if access_key is None or secret_key is None or authorization_token is None: print 'No AWS access key available.' sys.exit() # get VPS routing table to find the one assigned to our interface (via # vpc-id) r = call_aws_ec2('Action=DescribeRouteTables&Version=2016-11-15', region, access_key, secret_key, authorization_token) # find routeTableId used to manage the VPC on the interface of interest obj = etree.fromstring(r) table = obj.xpath('./routeTableSet/item[vpcId="%s"]' % vpc_id)[0] logging.debug(etree.tostring(table)) route_table_id = table.findtext('routeTableId') logging.debug("route_table_id = " + route_table_id) # Replace or add the route. Important: paramters must be alphanumerically sorted # in order to get accepted by aws ! request = 'Action=ReplaceRoute' \ + '&DestinationCidrBlock=' + ipv4_prefix.replace("/", "%2F") \ + '&NetworkInterfaceId=' + interface_id \ + '&RouteTableId=' + route_table_id \ + '&Version=2016-09-15' logging.debug("call_aws_ec2: " + request) r = call_aws_ec2(request, region, access_key, secret_key, authorization_token) logging.debug("response: " + r) obj = etree.fromstring(r) rv = obj.xpath('//return')[0] if rv.text == 'false': logging.nfo("ReplaceRoute failed: " + r) jcs.syslog("external.error", "ReplaceRoute failed: " + r) else: jcs.syslog( "external.notice", "set aws ec2 route " + ipv4_prefix + " via " + interface_id + " (" + interface + ") in " + route_table_id + " successful")
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()'''
def main(): snmp_action = jcs.get_snmp_action() snmp_oid = jcs.get_snmp_oid() #jcs.enable_debugger() # invoke lwaftr stats populate_stats() # log operation, oid message = "snmp_action: " message += snmp_action message += ", oid: " message += snmp_oid #jcs.syslog("external.info", message) """ if (lwaftr_statistics_dict.size() == 0): #fill null #return jcs.emit_snmp_attributes(snmp_oid, None, None) return """ if (snmp_action == "get"): operation = SNMP_GET elif (snmp_action == "get-next"): operation = SNMP_GETNEXT oid_list = snmp_oid.split(".") oid_list_len = len(oid_list) leaf = None instance_id = None protocol = None table_type = LW4OVER6_STAT_TABLE if (oid_list_len > 11): table_type = oid_list[11] table_type = int(table_type) if (table_type > LW4OVER6_INSTANCE_TABLE): return None if (table_type < LW4OVER6_STAT_TABLE): table_type = LW4OVER6_STAT_TABLE #.1.3.6.1.4.1.2636.1.7.151.1.1.<leaf> if (oid_list_len > 13): leaf = oid_list[13] leaf = int(leaf) message = "Table type " + str(table_type) #jcs.syslog("external.info", message) message = "Leaf value " + str(leaf) #jcs.syslog("external.info", message) if (oid_list_len > 14): instance_id = oid_list[14] instance_id = int(instance_id) if (table_type == LW4OVER6_STAT_TABLE): if (oid_list_len > 15): protocol = oid_list[15] protocol = int(protocol) if (table_type == LW4OVER6_STAT_TABLE and operation == SNMP_GETNEXT): (recv_leaf, recv_instance, recv_protocol, value) = snmp_getnext_value(leaf, instance_id, protocol) if (value is None): table_type = LW4OVER6_INSTANCE_TABLE instance_id = None leaf = None if (table_type == LW4OVER6_STAT_TABLE): message = "Parameters " if (leaf): message += "leaf: " + str(leaf) if (instance_id): message += " instance_id: " + str(instance_id) if (protocol): message += " protocol: " + str(protocol) #jcs.syslog("external.info", message) if (operation == SNMP_GET): #jcs.syslog("external.info", "get request") value = snmp_get_value(leaf, instance_id, protocol) if (value is None): jcs.syslog("external.info", "No entry available") return value = str(value) message = "value: " + value if (leaf == LWAFTR_INSTANCENAME): #message = message + " " + snmp_oid #jcs.syslog("external.info", message) return jcs.emit_snmp_attributes(snmp_oid, "string", value) else: return jcs.emit_snmp_attributes(snmp_oid, "Counter64", value) elif (operation == SNMP_GETNEXT): (recv_leaf, recv_instance, recv_protocol, value) = snmp_getnext_value(leaf, instance_id, protocol) if (value is None): jcs.syslog("external.info", "No entry available") return None; else: #jcs.syslog("external.info", value) pass #message = "Returning OID name: " oid_name = lw4overmib_table_oid + "." + str(recv_leaf) + "." + str(recv_instance) + "." + str(recv_protocol) #message += oid_name #jcs.syslog("external.info", message) if (recv_leaf == LWAFTR_INSTANCENAME): return jcs.emit_snmp_attributes(oid_name, "string", value) else: return jcs.emit_snmp_attributes(oid_name, "Counter64", value) else: jcs.syslog("external.info", "Unexpected SNMP operation") return else: message = "Parameters " if (leaf): message += "leaf: " + str(leaf) if (instance_id): message += " instance_id: " + str(instance_id) #jcs.syslog("external.info", message) if (operation == SNMP_GET): #jcs.syslog("external.info", "get request") value = snmp_get_instance_value(leaf, instance_id) if (value is None): jcs.syslog("external.info", "No entry available") return value = str(value) message = "value: " + value if (leaf == LWAFTR_INSTANCE_TABLE_NAME): #message = message + " " + snmp_oid #jcs.syslog("external.info", message) return jcs.emit_snmp_attributes(snmp_oid, "string", value) else: return jcs.emit_snmp_attributes(snmp_oid, "Counter64", value) elif (operation == SNMP_GETNEXT): (recv_leaf, recv_instance, value) = snmp_getnext_instance_value(leaf, instance_id) if (value is None): jcs.syslog("external.info", "No entry available") return None; else: #jcs.syslog("external.info", value) pass #message = "Returning OID name: " oid_name = lw4overmib_instance_table_oid + "." + str(recv_leaf) + "." + str(recv_instance) #message += oid_name #jcs.syslog("external.info", message) if (recv_leaf == LWAFTR_INSTANCE_TABLE_NAME): return jcs.emit_snmp_attributes(oid_name, "string", value) else: return jcs.emit_snmp_attributes(oid_name, "Counter64", value) else: jcs.syslog("external.info", "Unexpected SNMP operation") return
<file> <name>demo.py</name> </file> </op> </scripts> </system> </configuration> """ cu = Config(dev) try: cu.lock() cu.load(config_xml, format="xml", merge=True) cu.commit() cu.unlock() # Catch configuration lock error except LockError: jcs.syslog("external.error, Unable to lock configuration") dev.close() except ConfigLoadError: jcs.syslog("external.error, Unable to load configuration") cu.unlock() except CommitError: jcs.syslog("external.error, Unable to commit configuration") cu.unlock() except UnlockError: jcs.syslog("external.error,Unable to unlock configuration") dev.close()
def main(): script = os.path.basename(__file__) jcs.syslog( "external.info", "{0}: Python script triggered via ZTP to push configuration".format( script)) run_dir = "/var/db/scripts/event/" port_num = 30017 web_srvr_ip = '10.85.95.136' ztp_server = 'http://{0}:{1}/'.format(web_srvr_ip, port_num) conf_file = 'juniper.conf' storage_check = False jcs.syslog("external.info", "{0}: Downloading the configuration".format(script)) urllib.urlretrieve(ztp_server + conf_file, run_dir + conf_file) # Create a device object dev = Device(gather_facts=True) # Opens a connection dev.open() # Get system storage if storage_check: rsp = dev.rpc.get_system_storage() var_location_percent = rsp.xpath( ".//filesystem[normalize-space(mounted-on)='/var']/used-percent" )[0].text strip_percent = int(var_location_percent.strip()) if strip_percent > 75: syslog_message = "Warning: /var utilization is at " + str( strip_percent) + "%" jcs.syslog("external.warning", "{0}: {1}".format(script, syslog_message)) else: jcs.syslog( "external.info", "{0}: var location storage size {1}".format( script, strip_percent)) try: # Create configuration object with Config(dev, mode="exclusive") as cu: jcs.syslog("external.info", "{0}: Loading the configuration".format(script)) cu.load(path=run_dir + conf_file, overwrite=True) jcs.syslog("external.info", "{0}: Committing the configuration".format(script)) cu.commit() except Exception as err: jcs.syslog( "external.error", "{0}: Unable to commit the configuration {1}".format(script, err)) #print (err) dev.close() return jcs.syslog("external.info", "{0}: Successfully committed the configuration".format(script)) dev.close() jcs.syslog( "external.info", "{0}: Python script triggered to push config via ZTP is COMPLETED!!!!". format(script)) # Check cabling jcs.syslog( "external.info", "{0}: Sleeping for 60 secs before checking cabling connections!". format(script)) time.sleep(60) jcs.syslog("external.info", "{0}: Starting Cabling Verification.".format(script)) #compare_lldp_info() jcs.syslog("external.info", "{0}: Finished Cabling Verification.".format(script)) # Post end-ztp process webhook message jcs.syslog("external.info", "{0}: Post end-ztp process webhook message".format(script)) headers = {'Accept': 'application/json'} port_num = 32100 url = 'http://{0}:{1}/ztp-end-process'.format(web_srvr_ip, port_num) data = {"message": "ZTP process finished"} r = requests.post(url, data=json.dumps(data), headers=headers) jcs.syslog("external.info", "{0}: Post message output {1}".format(script, r.text))
def emit_info(message, silent): if silent: jcs.syslog("user.info", message) else: print message
def emit_error(message, silent): if silent: jcs.syslog("user.error", message) else: print message
if (value >= 0): lwaftr_entry.set_v6stat_value(LWAFTR_HCOCTETDROPS, value) continue value = populate_node_value(elem, 'drop-all-ipv6-iface-packets') if (value >= 0): lwaftr_entry.set_v6stat_value(LWAFTR_HCOPACKETDROPS, value) continue instance = lwaftr_instance_dict[instance_name] lwaftr_statistics_dict[instance] = lwaftr_entry message = "Added an entry: " + instance_name #jcs.syslog("external.info", message) except Exception as err: jcs.syslog("external.info", str(err)) jcs.emit_error("Uncaught esception: {0}".format(err)) def snmp_get_instance_value(leaf, instance): if instance is None: return None message = "Inside snmp_get_value " + "instance: " + str(instance) #jcs.syslog("external.info", message) lwaftr = lwaftr_statistics_dict[instance] #jcs.syslog("external.info", lwaftr) if lwaftr is None: jcs.syslog("external.info", "no entry") return None if (leaf == LWAFTR_INSTANCE_TABLE_NAME): return lwaftr.lwaftrName;