def main(): """ Main function """ interfaces_ietf = connect(NS) # if you want to see the XML parsed output, you can uncomment the line below. # print(DOM.parseString(interfaces_ietf.xml).toprettyxml()) doc = DOM.parseString(interfaces_ietf.xml) node = doc.documentElement inters_ietf = doc.getElementsByTagName("interface") for each in inters_ietf: ints = get_int_info(each) # print("%s, description: %s, enabled: %s" % (ints.name, ints.description, ints.enabled)) if ints.description == 'WAN': if ints.enabled == 'true': print "\n\n *** Adjusting QoS Policy on interface %s ***\n\n" % ints.name configuration = '''interface %s no service-policy output normal-egress-shape service-policy output linkdown-egress-shape end''' % ints.name cli.configurep(configuration) print "\n\n *** Now let's check the QoS Policy applied to the running WAN interface ***\n\n" cli.executep('show runn interface %s' % ints.name)
def configure_smart_licensing(idtoken, throughput): license_status = False throughput_status = False if idtoken is None: logger.warning("idtoken value is None. Please provide valid idtoken") return False smart_licensing_configuration = ''' license smart transport smart license smart url smart https://smartreceiver.cisco.com/licservice/license ''' logger.info("Trying to configure smart licensing. Configs: {}".format(smart_licensing_configuration)) for i in range(5): cli.configurep(smart_licensing_configuration) cli.executep('license smart trust idtoken {} local'.format(idtoken)) cli.configurep('platform hardware throughput level MB {}'.format(throughput)) output = cli.cli('show license tech support | inc ENABLED') if "Smart Licensing is ENABLED" in output: logger.info("Smart licensing successful") license_status = True output = cli.cli('sh platform hardware throughput level') logger.info("Throughput level set to: {}".format(output)) if str(throughput) in output: logger.info("Throughput level set successfully") throughput_status = True if license_status and throughput_status: logger.info("Successfully configured Smart Licensing and Throughput level") return True logger.warning("There were some issues with configuring Smart Licensing which did not succeed after 5 attempts. Please review configuration") return False
def configure_smart_licensing(email, idtoken, throughput): license_status = False throughput_status = False if idtoken is None: logger.warning("idtoken value is None. Please provide valid idtoken") return False smart_licensing_configuration = ''' service call-home call-home contact-email-addr {} profile "CiscoTAC-1" active destination transport-method http no destination transport-method email destination address http https://tools.cisco.com/its/service/oddce/services/DDCEService '''.format(email) logger.info("Trying to configure smart licensing. Configs: {}".format( smart_licensing_configuration)) for i in range(5): cli.configurep(smart_licensing_configuration) cli.executep('license smart register idtoken {}'.format(idtoken)) cli.configurep( 'platform hardware throughput level MB {}'.format(throughput)) time.sleep(30) output = cli.cli('show license summary') logger.info("Output of show license summary: {}".format(output)) if "Status: REGISTERED" in output: logger.info("Smart licensing successful") license_status = True output = cli.cli('sh platform hardware throughput level') logger.info("Throughput level set to: {}".format(output)) if str(throughput) in output: logger.info("Throughput level set successfully") throughput_status = True if license_status and throughput_status: logger.info( "Successfully configured Smart Licensing and Throughput level") return True logger.warning( "There were some issues with configuring Smart Licensing or Throughput level which did not succeed after 5 attempts. Please review configuration" ) return False
def print_line (text, step=None, width=40): stext="({})".format(step) if step else "***" if step: print "\n" print "***{}*** {} {}".format(stext, text, "*"*(width-len(text))) print_line("Checking hardware", 1) cli.executep("show platform | i Model|C9200|--\ ") print_line("Checking IOS version", 2) cli.executep("show version | i IOS XE") print_line("Generating RSA key", 3) cli.configurep("crypto key generate rsa modulus 2048 label sshv2logincert") print_line("Obtaining serial number", 4) license = cli.cli("show license udi") sn = license.split(":")[3].rstrip() print_line("Serial number is {}".format(sn)) print_line("Disabling copy prompts", 5) cli.configure("file prompt quiet") print_line("Copying configuration file from TFTP server", 6) cli_command = "copy tftp://{}/config/{}.txt startup-config vrf Mgmt-vrf".format (tftp_server, sn.lower()) cli.executep(cli_command) time.sleep (5) print_line("Verifying received startup config...", 7) host_line=cli.cli("show startup-config | i hostname").split() # actual output will be "Using xxxx out of 2097152 byteshostname sw9200-1A" if host_line: host_name=host_line[-1] # last entry print_line("Configuration for {} downloaded successfully!".format(host_name)) print_line("Rebooting with the new config!", 8) cli.cli("reload") else: print("*** *** *** Configuration failed *** *** ***")
print "\n\n *** Sample ZTP Day0 Python Script *** \n\n" # Importing cli module import cli print "Configure vlan interface, gateway, aaa, and enable netconf-yang\n\n" cli.configurep( ["int vlan 1", "ip address 10.5.123.27 255.255.255.0", "no shut", "end"]) cli.configurep(["ip default-gateway 10.5.123.1", "end"]) cli.configurep(["username admin privilege 15 secret 0 XXXXXXXXXXXXX"]) cli.configurep( ["aaa new-model", "aaa authentication login default local", "end"]) cli.configurep( ["aaa authorization exec default local", "aaa session-id common", "end"]) cli.configurep(["netconf-yang", "end"]) print "\n\n *** Executing show ip interface brief *** \n\n" cli_command = "sh ip int brief" cli.executep(cli_command) print "\n\n *** ZTP Day0 Python Script Execution Complete *** \n\n"
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (c) 2019 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at https://developer.cisco.com/docs/licenses All use of the material herein must be in accordance with the terms of the License. All rights not expressly granted by the License are reserved. Unless required by applicable law or agreed to separately in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ import cli commands = [ "show version", ] for c in commands: cli.executep(c)
Execute Cisco IOS CLI exec-mode command and return the result. command_output = execute("show version") Args: command (str): The exec-mode command to run. Returns: str: The output of the command. Raises: CLISyntaxError: If there is a syntax error in the command. help(executep) Help on function executep in module cli: executep(command) Execute Cisco IOS CLI exec-mode command and print the result. executep("show version") Args: command (str): The exec-mode command to run. help(cli) Help on function cli in module cli: cli(command) Execute Cisco IOS CLI command(s) and return the result.
import sys import cli print "\n\n *** Shutting Down BGP Session *** \n\n" cli.configurep(["router bgp 100","neighbor 10.1.2.2 shutdown", "end"]) print "\n\n *** Show BGP Status *** \n\n" cli.executep('show bgp summary')
config_cmds = [ "hostname ZTP-{}".format(sn), "ip ssh version 2", "ip ssh logging events", "crypto key generate rsa modulus 2048", "username cisco privilege 15 secret cisco", "enable secret cisco", "netconf-yang", "cdp run", "line vty 0 4", "login local", "transport input ssh", "interface Loopback0", "ip address {} 255.255.255.255".format(lb0_ip), "ip ospf 1 area 0", "interface Tunnel100", "description DMVPN SPOKE TUNNEL", "ip address {} 255.255.255.0".format(tun100_ip), "cdp enable", "ip nhrp network-id 100", "ip nhrp nhs dynamic nbma connect.imejia.com multicast", "ip ospf network point-to-multipoint", "ip ospf 1 area 0", "tunnel source GigabitEthernet3", "tunnel mode gre multipoint" ] print "\n* Performing ZTP configuration" cli.configurep(config_cmds) # Ensure each feature was configured successfully by running some "show" commands and displaying the output on the screen. print "\n* Performing ZTP verification" show_cmds = [ "show ip ssh", "show ip interface brief", "show dhcp lease", "show ip ospf interface brief" ] for show_cmd in show_cmds: print "\n* Running command '{}'".format(show_cmd) cli.executep(show_cmd)
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # #THIS SCRIPT IS DESIGNED TO BE RUN FROM AN EXTERNAL MACHINE HAVING TELNET ACCESS TO NETWORK DEVICES. import re, cli #Get a copy of the ARP table in Mgmt-vrf arp_table = cli.execute('show ip arp vrf Mgmt-vrf') cli.executep('show ip arp vrf Mgmt-vrf') #Find all IP addresses in the ARP table hosts = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", arp_table) if hosts: for host in hosts: #ping each IP address ping_result = cli.execute("ping vrf Mgmt-vrf %s timeout 1" % host) #See if ping was successful success = re.findall(r"Success rate is 100 percent", ping_result) if success: cli.execute("send log %s is reachable" % host) else: cli.execute("send log %s is NOT reachable" % host)
print("\n Welcome to ZTP! \n") import sys print(" Python version is \n") print(sys.version) print("\n\n") import time import cli import traceback print("\n HellO! \n") cli.configurep("hostname shishir") cli.executep("show version") import os os.system("sudo ifconfig") os.system("sudo route -n") cli.executep("show ip int br") cli.executep("show ip int br | i up") cli.executep("show run int vlan1") cli.executep("show run int vlan4094") cli.executep("show run | s iox") cli.executep("show run | s app-h") cli.executep("show lic all")
import cli eem = ''' event manager applet upgrade event none maxrun 400 action 1.0 cli command "enable" action 2.0 cli command "request platform software package expand file bootflash:cbrsup-universalk9.16.12.01z.SPA.bin to bootflash:/XE-1612-1z/ wipe" ''' cli.configurep(eem) request = "event manager run upgrade" cli.executep(request)
print "\n\n *** Sample ZTP Day0 Python Script IMEJIA DEVNET *** \n\n" # Importing cli module import cli print "\n\n *** Executing show version *** \n\n" cli.executep("show version") print "\n\n *** Configuring a Loopback Interface *** \n\n" cli.configurep( ["interface loop 100", "ip address 10.10.10.10 255.255.255.255", "end"]) print "\n\n *** Executing show ip interface brief *** \n\n" cli.executep("show ip int brief") print "\n\n *** ZTP Day0 Python Script Execution Complete *** \n\n"
print "\n* Running command '{}'".format(cmd) upgr_qc.append(cli.execute(cmd)) bootsys_cmds = [ "no boot system", "boot system bootflash:/XE-1612-1z/packages.conf", "boot system bootflash:/cbrsup-universalk9.16.12.01z.SPA.bin" ] x = cli.configure(bootsys_cmds) cli.executep("write mem") with open("/bootflash/{}.log".format(sn), "a") as f: for i in range(len(qc_str)): f.write("#############START OF SEGMENT##############\n") f.write("") f.write(qc_str[i]) f.write("") f.write("#############END OF SEGMENT##############\n") with open("/bootflash/{}.log".format(sn), "a") as f: for i in range(len(upgr_qc)): f.write("#############START OF SEGMENT##############\n") f.write("") f.write(upgr_qc[i]) f.write("")
def enable_ipxe(): print("*** Enabling iPXE to upgrade software ***\n") cli.configurep(["boot ipxe timeout 30"]) cli.executep("copy running-config startup-config") cli.executep("reload /noverify")
print("\nConfiguring interface %s with 'configurep' function...\n") % intf cli.configurep([ "interface " + intf, "ip address 10.55.55.55 255.255.255.0", "no shut", "end" ]) print("\nConfiguring interface %s with 'configure' function...\n") % intf cmd = 'interface %s,logging event link-status,end' % intf cli.configure(cmd.split(',')) print("Printing show command output with 'executep' function...\n") cli.executep('show ip interface brief') print("\nPrinting show command with 'execute' function...\n") output = cli.execute('show run interface %s' % intf) print(output) print("\nConfiguring interface %s with 'cli' function...\n" % intf) cli.cli( 'config terminal; interface %s; description Configured with a Python script from Guest Shell' % intf) print("Printing show command with 'clip' function...")
def disable_ipxe(): print("*** Disabling iPXE ***\n") cli.configurep(["no boot ipxe timeout 30"]) cli.executep("copy running-config startup-config")
import cli print "\n\n **Executing show version** \n\n" cli_command = "show version" cli.executep(cli_command) print "\n\n **Executing show inventory** \n\n" cli_command = "show inventory" cli.executep(cli_command) device_type = cli.executep(cli_command) print "\n\n **Download Image** \n\n" cli_command = "copy tftp://169.254.0.1/cat9k_iosxe.16.09.03.SPA.bin flash:" cli.executep(cli_command) print "\n\n **Copy Base Config** \n\n" cli_command = "copy tftp://169.254.0.1/base_config flash:" cli.executep(cli_command) int "\n\n **Copy Base Config** \n\n" cli_command = "copy flash:base_config running-config" cli.executep(cli_command) #print "\n\n **Configure BootVAR** \n\n" #cli_command = "boot system flash:cat9k_iosxe.16.09.03.SPA.bin" #cli.configurep(cli_command)