コード例 #1
0
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)
コード例 #2
0
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 *** *** ***")
コード例 #3
0
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
コード例 #4
0
def base_config():
    print "\n\n *** Setting hostname *** \n\n"
    configure('hostname ZTP-Success')
    print "\n\n *** Configuring local ansible user and enable secret *** \n\n"
    configure('username {} privilege 15 password {}'.format(USER, PASS))
    configure('enable secret {}'.format(SECRET))
    print "\n\n *** Configuring FTP user and pass for code retrieval *** \n\n"
    configure('ip ftp username {}'.format(FTPUSER))
    configure('ip ftp password {}'.format(FTPPASS))
    print "\n\n *** Setting vty logins to authenticate locally *** \n\n"
    configurep(['line vty 0 4', 'login local'])
コード例 #5
0
def delete_span(sessionID):

   '''
   INPUT
       Input on the function is session ID which will be used to delete via CLI

   OUTPUT
       None    
   '''

   cli.configurep("no monitor session \{0\}".format(sessionID))
コード例 #6
0
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
コード例 #7
0
print "\n\n *** Sample ZTP Day0 Python Script *** \n\n"
# Importing cli module
import cli

print "Configure hostname, vlans, and others\n\n"

cli.configurep(["hostname C93-Services"])

cli.configurep(["license boot level network-advantage addon dna-advantage"])

cli.configurep(["ip routing"])
cli.configurep(["ip domain name cisco.com"])

cli.configurep(
    ["interface loopback 0", "ip address 10.0.114.5 255.255.255.255", "end"])

cli.configurep([
    "interface TenGigabitEthernet1/1/1",
    "description L2-to-C9404-SVL-Te1/2/0/4 ", "switchport access vlan 100",
    "switchport mode access", "end"
])
cli.configurep([
    "interface TenGigabitEthernet1/1/2",
    "description L2-to-C9404-SVL-Te2/2/0/4 ", "switchport access vlan 100",
    "switchport mode access", "end"
])

cli.configurep(["username admin privilege 15 secret Cisco123"])
cli.configurep(["username admin2 privilege 15 secret Cisco456"])

cli.configurep(["snmp-server community Public RO "])
コード例 #8
0
#!/usr/bin/env python

import sys
import cli

intf = sys.argv[1:]
intf = ''.join(intf[0])

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)
コード例 #9
0
Python scripts can run in non-interactive mode by providing the Python script name as an argument in the Python command. Python scripts must be accessible from within the Guest Shell. To access Python scripts from the Guest Shell, save the scripts in bootflash/flash that is mounted within the Guest Shell.

The following sample Python script uses different CLI functions to configure and print show commands:

Device# more flash:sample_script.py


import sys
import cli

intf= sys.argv[1:]
intf = ''.join(intf[0])

print "\n\n *** Configuring interface %s with 'configurep' function  *** \n\n" %intf
cli.configurep(["interface loopback55","ip address 10.55.55.55 255.255.255.0","no shut","end"])

print "\n\n *** Configuring interface %s with 'configure' function  *** \n\n"
cmd='interface %s,logging event link-status ,end' % intf
cli.configure(cmd.split(','))

print "\n\n *** Printing show cmd with 'executep' function  *** \n\n"
cli.executep('show ip interface brief')

print "\n\n *** Printing show cmd with 'execute' function  *** \n\n"
output= cli.execute('show run interface %s' %intf)
print (output)

print "\n\n *** Configuring interface %s with 'cli' function  *** \n\n"
cli.cli('config terminal; interface %s; spanning-tree portfast edge default' %intf)
コード例 #10
0
def get_span_sessionID():

# I will use matplotlib to draw the price per day in Boston and Seattle. 
# That require the dataset format to be change from string to integer/float to be able to plot.
# Function "clean_astype_date" converts 'date' to datetime64 type and 'price' to float64

def clean_astype_date(df, price_per_day):

    '''
    INPUT 
        Input on the function will come from CLI execution 
        
    OUTPUT
        Apply regexp to filter the session ID or return 0
    '''
    
    output = cli.execute('show run | in monitor')

    for span_line in output.splitlines():
        p = re.compile(r'^monitor session ([0-9]+).*')
        m = p.match(span_line)
        if m:
            return m.group(1)
    return 0

def get_span_port(span_session):

    '''
    INPUT 
        Input on the function will come from CLI execution using Session ID                               

    OUTPUT
        Apply regexp to filter the interface destination for session ID or return 0
    '''
    

    output = cli.execute('show run | in monitor')
    for span_line in output.splitlines():
        p = re.compile(r'^monitor session [0-9]+ destination interface (.*)')
        m = p.match(span_line)
        if m:
            return m.group(1)

    return 0

def get_span_config():

    '''
    INPUT 
        Input on the function will come from CLI execution                               

    OUTPUT
        Return the monitor session Config or empty 
    '''
    

    output = cli.execute('show run | in monitor')
    span_config = []
    for span_line in output.splitlines():
        span_config.append(span_line)

    return span_config

def delete_span(sessionID):

   '''
   INPUT
       Input on the function is session ID which will be used to delete via CLI

   OUTPUT
       None    
   '''

   cli.configurep("no monitor session \{0\}".format(sessionID))

def span_port_occupancy(span_port):

  '''
  INPUT
      Input on the function will come from CLI execution using the SPAN Port ID

  OUTPUT
       Return the queue real time occupancy per queue for the SPAN port in units. the return is a list. 
  '''

  output = cli.execute('show platform hardware fed active qos queue stats interface {0} | section include [0-9][ ]+[0-9]+.*'.format(span_port))

  queues_only = 0
  All_queues_occupancy = {}
  for queue_buffer in output.splitlines():
      p = re.compile(r'^([0-9]+)[ ]+([0-9]+).*')
      m = p.match(queue_buffer)
      if m:
          Queue_ID = m.group(1)
          occupancy = int(m.group(2))
          All_queues_occupancy.update({Queue_ID : occupancy})

      queues_only = queues_only + 1
      if queues_only == 9:
          break


  return All_queues_occupancy

def span_port_totalbuffer_units(span_port):

  '''
  INPUT
      Input on the function will come from CLI execution using the SPAN Port ID 

  OUTPUT
      Return per queue total number of units give to queue. the return is a list
  '''

  output = cli.execute('show platform hardware fed active qos queue config interface {0} | begin DTS'.format(span_port))

  queues_only = 0
  All_queues_buffers = {}
  for queue_buffer in output.splitlines():
      p = re.compile(r'^[ ]([0-9]+)[ ]+[0-9]+[ ]+[0-9]+[ ]+[0-9]+[ ]+[0-9]+[ ]+([0-9]+).*')
      m = p.match(queue_buffer)

      if m:
          Queue_ID = m.group(1)
          Buffers = int(m.group(2))
          All_queues_buffers.update(\{Queue_ID : Buffers\}) 

      queues_only = queues_only + 1
      if queues_only == 11:
          break


  return All_queues_buffers


if __name__ == '__main__':

   # Get SPAN Config in case we need to reconfigure it back
   span_config = get_span_config()

   # Get SPAN Session Port
   span_port = get_span_port(get_span_sessionID)

   # Get SPAN Session ID
   sessionID = get_span_sessionID() 

   # Substract and find the difference between total and occupied. If the occupancy per queue is more than 80% remove the SPAN
   d1 = span_port_totalbuffer_units(span_port)
   d2 = span_port_occupancy(span_port)
   for k, v in d1.items():
      if v > 0:
         cmd = "echo " + "\'a Queue is Occupied above 80%: {0} \'".format(float(d2.get(k, 0))/float(v)) + " > /dev/ttyS2"
         os.system(cmd)
         time.sleep(2)
         if float(d2.get(k, 0))/float(v) > 0.8:
             cmd = "echo " + "\'Deleting SPAN session with ID: {0} \'".format(sessionID) + " > /dev/ttyS2"
             os.system(cmd)
             time.sleep(2)
             delete_span(sessionID)
             cmd = "echo " + "\'Session is Deleted\'" + " > /dev/ttyS2"
             os.system(cmd)
             time.sleep(2)

             break

   cmd = "echo " + "\'Waiting for 20 secs\'" + " > /dev/ttyS2"
   os.system(cmd)
   time.sleep(20)

   # Reconfigure the session after 20 seconds as the Microburst condition might have disappeared.
   cmd = "echo " + "\'Reconfigure the SPAN session with ID: {0}\'".format(sessionID) + " > /dev/ttyS2"
   os.system(cmd)

   cli.configurep(span_config)
コード例 #11
0
from cli import executep, execute, configurep, cli
import re
import urllib.request

print("\n *** Sample ZTP Day0 Python Script *** \n")

print("\n *** Configuring SSH access *** \n")
configurep(["username temp privilege 15 secret temp"])
configurep(["ip domain name test.local", "hostname RTR"])
configurep(["crypto key gen rsa mod 2048"])
configurep([
    "line vty 0 4", "login local", "transport input all", "exec-timeout 15",
    "end"
])

print("\n ***Getting Serial number ( identifier ) *** \n")
sn = execute("sh ver | i board ID")
sn = re.split(r'\s', sn)[3]
print("SERIAL NUMBER : {}".format(sn))

print("\n ***Call back for config and provide identifier (SN)  *** \n")
url = "http://10.1.1.10/get_config"
headers = {'Serial': sn}
req = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(req)
response = response.read()
print("RESPONSE : {}".format(response))
print("\n *** ZTP Day0 Python Script Execution Complete *** \n")
コード例 #12
0
print "Failed configurations:"
for failure in e.failed:
print failure

Args:
configuration (str or iterable): Configuration commands, separated by newlines.

Returns:
list(ConfigResult): A list of results, one for each line.

Raises:
CLISyntaxError: If there is a syntax error in the configuration.

    help(configurep)
Help on function configurep in module cli:

configurep(configuration)
Apply a configuration (set of Cisco IOS CLI config-mode commands) to the device
and prints the result.

configuration = '''interface gigabitEthernet 0/0
no shutdown'''

# push it through the Cisco IOS CLI.
configurep(configuration)

Args:
configuration (str or iterable): Configuration commands, separated by newlines.
    help(execute)
Help on function execute in module cli:
コード例 #13
0
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"
コード例 #14
0
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)
コード例 #15
0
        "echo \"export no_proxy=.x.x.x.x.com\" | sudo tee -a /etc/bashrc",
        "echo \"export HTTP_PROXY=http://x.x.x.x:80/\" | sudo tee -a /etc/bashrc",
        "echo \"export HTTPS_PROXY=http://x.x.x.x:80/\" | sudo tee -a /etc/bashrc",
        "echo \"export FTP_PROXY=http://x.x.x.x:80/\" | sudo tee -a /etc/bashrc"
    ]
    for command in commands_to_run_on_gs:
        p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
        (output, err) = p.communicate()
        print "Linux command output is", output


# main code:
if __name__ == '__main__':

    # these commands are need to remove msec and add year in the show log command
    cli.configurep("service timestamps log datetime")
    cli.configurep("service timestamps log datetime year")

    port_flaps_cnt = 0
    interface = None
    port_flaps = checkPortFlap(port_flaps_cnt, interface)

    if (port_flaps[0] == 10):
        if (port_flaps[1] is not None):
            print("shutting down interface %s" % (port_flaps[1]))

            # shut down the interface using cli module
            #cli(["interface %s" % (port_flaps[1]), "shut", "end"])
            cli.configurep(["interface %s" % (port_flaps[1]), "shut", "end"])

            # wait for 5 mins to monitor the interface flap again
コード例 #16
0
import sys
import cli

intf = sys.argv[1:]
intf = ''.join(intf[0])

cli.configurep(["int %s" % intf, "no shutdown", "end"])
コード例 #17
0
ファイル: ex02.py プロジェクト: Tubbz-alt/DEVWKS-1836
#!/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

configuration = '''hostname pythonrocks
'''

cli.configurep(configuration)
コード例 #18
0
import cli
from cli import configurep
from cli import executep

print "\n\n *** Sample ZTP Day0 Python Script *** \n\n"
cli.configurep(["hostname JCOHOE-9840-ZTP"])
print "Configure vlan interface, gateway, aaa, and enable netconf-yang\n\n"
cli.configurep([
    "int GigabitEthernet0", "ip address 10.85.134.78 255.255.255.192",
    "no shut", "end"
])
cli.configurep(["username admin privilege 15 secret 0 Cisco123"])
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"])
cli.configurep(["ip http secure-server", "restconf", "end"])
cli.configurep(
    ["line vty 0 15", "transport input all", "exec-timeout 0 0", "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"
コード例 #19
0
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)
コード例 #20
0
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"
コード例 #21
0
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')
コード例 #22
0
ファイル: ZTP_demo.py プロジェクト: shashasi/BRKRST-2600
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# Importing cli module
import cli,re

print "\n\n *** ZTP Python Script *** \n\n"

#Define credentials for ZTP switch
user = "******"
password = "******"
enable = "cisco"

#Configure hostname on ZTP switch
print "\n\n *** Configuring hostname *** \n\n"
cli.configurep(["hostname ZTP-Switch", "end"])

#Configure credentials on ZTP switch
print "\n\n *** Configuring credentials *** \n\n"
cli.configurep(['username {} privilege 15 password {}'.format(user, password)]) 
cli.configurep(['enable secret {}'.format(enable)])

#Configure telnet and ssh on ZTP switch
print "\n\n *** Configuring telnet & ssh *** \n\n"
cli.configurep(['line vty 0 4', 'login local', 'transport input telnet ssh'])

#get show interface status output from ZTP switch
list = cli.execute('show interface status')

#Find all 1G ports
gig_ports = re.findall(r"(Gi\d\/\d\/\d{1,2}).+?connect", list)
コード例 #23
0
or implied.

"""

__author__ = "Juulia Santala"
__email__ = "*****@*****.**"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2020 Cisco and/or its affiliates."
__license__ = "Cisco Sample Code License, Version 1.1"

# Import cli python module. This will let you use the cli commands
# from python.
import cli

#cli.configurep pushes commands to the switch!
cli.configurep(
    ["int vlan 42", "ip address 10.2.0.13 255.255.255.0", "no shut", "end"])
cli.configurep(["ip default-gateway 10.2.0.1", "end"])
cli.configurep(["username admin privilege 15 secret 0 admin"])
cli.configurep(
    ["aaa new-model", "aaa authentication login default local", "end"])
cli.configurep(
    ["aaa authorization exec default local", "aaa session-id common", "end"])

# Save a show command, and use cli.executep to execute it and
# print it on screen.
cli_command = "sh ip int brief"
cli.executep(cli_command)

#Finally, we print a text on screen to show the execution is complete.
print("\n\n *** ZTP Day0 Python Script Execution Complete *** \n\n")
コード例 #24
0
print "\n\n *** Sample ZTP Day0 Python Script *** \n\n"
# Importing cli module
import cli
print "\n\n *** Configuring gig 0 *** \n\n"
cli.configurep(["interface gi0", "ip address dhcp", "no shut", "end"])
print "\n\n *** Configure Generic Username and password *** \n\n"
cli.configurep(
    ["username admin password Password1", "enable password Password1"])
print "\n\n *** Configure Hostname *** \n\n"
cli.configurep(["hostname Device"])
print "\n\n *** Generate Crypto Keys *** \n\n"
cli.configurep(["crypto key gen rsa mod 1024"])
print "\n\n *** IP domain *** \n\n"
cli.configurep(["ip domain-name cisco.com"])
print "\n\n *** Set SSH version 2 *** \n\n"
cli.configurep(["ip ssh version 2"])
print "\n\n *** Set ssh transport *** \n\n"
cli.configurep(["line vty 0 15", "transport input ssh", "login local"])
print "\n\n *** Executing Save *** \n\n"
cli_command = "copy run start"
cli.executep(cli_command)
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"
コード例 #25
0
Learning Series: Network Programmability Basics
Module: Application Hosting
Lesson: Python at the Edge
Author: Hank Preston <*****@*****.**>

eem_intf_up.py
Illustrate the following concepts:
- Run a Python script due to EEM event
- Leverage the Python API library "cli"
"""

__author__ = "Hank Preston"
__author_email__ = "*****@*****.**"
__copyright__ = "Copyright (c) 2016 Cisco Systems, Inc."
__license__ = "MIT"

from cli import configurep
import argparse

# Retrieve the interface from command line using argparse
parser = argparse.ArgumentParser()
parser.add_argument("interface", help="Interface to bring up")
args = parser.parse_args()

# List of commands to run
commands = ["interface {}".format(args.interface), "no shut"]

# Run commands using Python API
# Commands need to be semicolon seperated
configurep(commands)
コード例 #26
0
# python -m py_compile sample_python_day0.py

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")