def main(): # Create table/view definition yaml_data = \ """--- ttyTable: rpc: get-system-users-information item: uptime-information/user-table/user-entry key: tty view: ttyView ttyView: fields: user: user from: from login_time: login-time idle_time: idle-time command: command """ # Load table/view into global namespace globals().update(FactoryLoader().load(yaml.load(yaml_data))) # Setup argument parsing for dynamic config parser = argparse.ArgumentParser() parser.add_argument('-tty', required=True) args = parser.parse_args() try: # create device object dev = Device(gather_facts=False) # open connection to device dev.open() try: # Create table tty = ttyTable(dev) # Fetch data for tty tty.get(args.tty) # Print some data from the view print "User: {0}, from: {1}".format(tty[0]['user'], tty[0]['from']) # Catch configuration RPC error except RpcError as err: jcs.emit_error("Unable to execute RPC: {0}".format(err)) dev.close() return dev.close() except Exception as err: jcs.emit_error("Uncaught exception: {0}".format(err))
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(): # Get configuration root object root = Junos_Configuration # Check for 'ssh' configuration if not (root.xpath("./system/services/ssh")): jcs.emit_error("SSH must be enabled.") # Ensure that user account jnpr exists if not (root.xpath("./system/login/user[name='jnpr']")): jcs.emit_error("The jnpr user account must be created.") # Verify that fxp0 has an IP address fxp0_interface_ip = root.xpath( "./interfaces/interface[name='fxp0']/unit[name='0']/family/inet/address/name" ) if not (fxp0_interface_ip): jcs.emit_error("fxp0 must have an IP address.")
def main(): jcs.emit_error("Error message from a Python automation script")
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 '''
counter_pattern = re.compile("(\s+\d+)") for line in output.splitlines(): l_line = line.lower() for x in EXCEPT: # skip line based on keywords if x in l_line: print(line) break else: # humanize values matches = counter_pattern.finditer(line) if matches: i = 0 # string position humanized_line = [] for match in matches: # replace subscring humanized_line.append(line[i:match.start()]) humanized_line.append(humanize(match.group(1), decimal)) i = match.start() + len(match.group(1)) humanized_line.append(line[i:]) # append remaining print("".join(humanized_line)) else: print(line) if __name__ == '__main__': try: main() except Exception as error: jcs.emit_error(str(error))
counter_pattern = re.compile("(\s+\d+)") for line in output.splitlines(): l_line = line.lower() for x in EXCEPT: # skip line based on keywords if x in l_line: print(line) break else: # humanize values matches = counter_pattern.finditer(line) if matches: i = 0 # string position humanized_line = [] for match in matches: # replace subscring humanized_line.append(line[i:match.start()]) humanized_line.append(humanize(match.group(1), decimal)) i = match.start() + len(match.group(1)) humanized_line.append(line[i:]) # append remaining print("".join(humanized_line)) else: print(line) if __name__ == '__main__': try: main() except Exception as error: jcs.emit_error(str(error))
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; if (leaf == LWAFTR_INSTANCE_TABLE_BREATHS):