예제 #1
0
def apply_config(target):
    """ Returns True if configuration template is applied successfully """
    cfg_url = urljoin(target.base_url,
                      target.config) if target.config else None

    # remove keyword 'end' from downloaded configuration
    conf = re.sub('^\s*end\s*$', '', download(cfg_url), flags=re.MULTILINE)
    if target.template:
        conf += '\n' + target.template if len(conf) else target.template

    if len(conf) == 0:
        return False

    # build configuration from template by $-based substitutions
    if target.subst:
        conf = Template(conf).safe_substitute(target.subst)

    # apply configuration and log error message in case of failure
    try:
        cli.configure(conf)
    except cli.CLIConfigurationError as e:
        log(3, 'Failed configurations:\n' + '\n'.join(map(str, e.failed)))
        shutdown(save=False, abnormal=True)  # terminate script
    else:
        return True
예제 #2
0
def stop_capture(job_id, filename):
    cli.execute("monitor capture PKT_CAP stop")
    cmd = "monitor capture PKT_CAP export flash:%s" % filename
    cli.execute(cmd)
    configuration = 'no ip access-list extended PKT_CAP'  # delete capture ACL so next capture has a fresh filter
    cli.configure(configuration)
    print('job_id %d stopped' % job_id)
예제 #3
0
파일: ztp.py 프로젝트: boclay/IOS-XE-ZTP
def configure_IBNS2():
    # Copy and merge IBNS 2.0 template into running-config
    configure('file prompt quiet')
    execute('copy http://192.168.1.100/IBNS2.cfg running-config')
    print '\n\n\n\n****************************************\n'
    print 'IBNS 2.0 template applied...'
    print '\n****************************************\n\n'
예제 #4
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 *** *** ***")
예제 #5
0
def find_certs():
    certs = cli('show run | include crypto pki')
    if certs:
        certs_split = certs.splitlines()
        certs_split.remove('')
        for cert in certs_split:
            command = 'no %s' % (cert)
            configure(command)
예제 #6
0
def base_config():
    configure(['hostname adam-ztd'])
    configure(['username {} privilege 15 password {}'.format(USER, PASSWORD)])
    configure(['enable secret {}'.format(ENABLE)])
    configure(['line vty 0 4', 'login local'])
    print "\n *** restconf *** \n"
    configure(['restconf'])
    print "\n *** sleeping 20 ** \n"
    time.sleep(20)
예제 #7
0
def start_capture(proto, src, dst):
    configuration = acl_command(proto, src, dst)
    cli.configure(configuration)
    cli.execute(
        "monitor capture PKT_CAP access-list PKT_CAP buffer circular size 100")
    cmd = "monitor capture PKT_CAP interface %s both" % args.interface
    cli.execute(cmd)
    cli.execute("monitor capture PKT_CAP clear")
    cli.execute("monitor capture PKT_CAP start")
예제 #8
0
def configure_network(**kwargs):
    if 'ip' in kwargs and kwargs['ip'] is not None:
        log('Configuring IP address: {}'.format(kwargs['ip']), 5)
        configure([
            'int g0/0', 'ip address {} {}'.format(kwargs['ip'],
                                                  kwargs['netmask'])
        ])
        configure(
            ['ip route vrf Mgmt-vrf 0.0.0.0 0.0.0.0 {}'.format(kwargs['gw'])])
예제 #9
0
def reschedule(seconds, diff):
    UPDATE_SCRIPT_FIRING_COMMANDS = """
 event manager applet ACL-SYNC-CHECK
 event timer watchdog time %s
 action 1.0 cli command "enable"
 action 1.1 cli command "guestshell run /home/guestshell/check_acl_sync.py
"""
    configure(UPDATE_SCRIPT_FIRING_COMMANDS % (seconds))
    if diff:
	    log(diff,4)
예제 #10
0
def start_capture(job_id, iface, proto, src, dst):
    configuration = acl_command(proto, src, dst)
    cli.configure(configuration)
    cli.execute(
        "monitor capture PKT_CAP access-list PKT_CAP buffer circular size 100")
    cmd = "monitor capture PKT_CAP interface %s both" % iface
    cli.execute(cmd)
    cli.execute("monitor capture PKT_CAP clear")
    print('job_id %d starting' % job_id)
    cli.execute("monitor capture PKT_CAP start")
예제 #11
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'])
예제 #12
0
def config_qos(interface, policymap, desired):
    if desired is False:
        prefix = "no "
    else:
        prefix = ""

    cli.configure([
        "interface {}".format(interface),
        "{}service-policy output {}".format(prefix, policymap),
        "end",
    ])
예제 #13
0
def delete_usernames(usuarios):

    from cli import configure

    for usuario in usuarios:
        comando = "no username " + usuario
        print('Borrando usuario', usuario)
        try:
            configure(comando)
            print('Usuario', usuario, 'borrado')
        except Exception as error:
            raise ValueError('Error al borrar usuario: ' + str(error))
예제 #14
0
def main():
    print '\n\n\n\n###### STARTING ZTP SCRIPT ######'
    print '\n*** Obtaining serial number of device.. ***'
    serial = get_serial()
    print '*** Setting configuration file variable.. ***'
    config_file = "{}.cfg".format(serial)
    print '\n*** Config file: %s ***' % config_file

    if upgrade_required():
        print '\n*** Upgrade is required. Starting upgrade process.. ***\n'
        if check_file_exists(img_cat9k):
            if not verify_dst_image_md5(img_cat9k, img_cat9k_md5):
                print '\n*** Attempting to transfer image to switch.. ***'
                file_transfer(tftp_server, img_cat9k)
                if not verify_dst_image_md5(img_cat9k, img_cat9k_md5):
                    raise ValueError('Failed Xfer')
        else:
            file_transfer(tftp_server, img_cat9k)
            if not verify_dst_image_md5(img_cat9k, img_cat9k_md5):
                raise ValueError('XXX Failed Xfer XXX')

        print '\n*** Deploying EEM upgrade script ***'
        deploy_eem_upgrade_script(img_cat9k)
        print '\n*** Performing the upgrade - switch will reboot ***\n'
        cli('event manager run upgrade')
        time.sleep(600)
    else:
        print '\n*** No upgrade is required!!! ***'

    # Cleanup any leftover install files
    print '\n*** Deploying Cleanup EEM Script ***'
    deploy_eem_cleanup_script()
    print '\n*** Running Cleanup EEM Script ***'
    cli('event manager run cleanup')
    time.sleep(30)

    if not check_file_exists(config_file):
        print '\n*** Xferring Configuration!!! ***'
        file_transfer(tftp_server, config_file)
        time.sleep(10)
    print '\n*** Removing any existing certs ***'
    find_certs()
    time.sleep(10)

    print '\n*** Deploying Configuration ***'
    try:
        configure_replace(config_file)
        configure('crypto key generate rsa modulus 4096')
    except Exception as e:
        pass
    print '\n###### FINISHED ZTP SCRIPT ######'
예제 #15
0
def autoupgrade():
    """ Returns True if autoupgrade script is configured or False otherwise """
    switch = cli.execute('show switch')
    # look for a switch in version mismatch state
    if switch.find('V-Mismatch') > -1:
        # Workaround to execute interactive marked commands from guestshell
        cli.configure('''event manager applet upgrade
            event none maxrun 600
            action 1.0 cli command "enable"
            action 2.0 cli command "request platform software package install autoupgrade"
            action 3.0 syslog msg "Reloading stack..."
            action 4.0 reload''')
        return True
    else:
        return False
예제 #16
0
def remove_routes(routes, version, vrf=None, interactive=True):
    """Remove routes from the router configuration
    
    Args:
        routes[] (str): list of routes to be added
        version (int): IP version (4/6)
        vrf (str): VRF name
        interactive (bool): run in interactive mode (ask user to confirm)
        
    Returns:
        IOS CLI command string.
    
    """
    if interactive:
        log_message(
            "{} IPv{} routes to be removed fro VRF  \"{}\": \n{}\n\n".format(
                len(routes), version, vrf, routes), interactive)
    else:
        log_message(
            "{} IPv{} routes to be removed from VRF \"{}\"".format(
                len(routes), version, vrf), interactive)

    response = raw_input("Perform action? y/N ") if interactive else "y"
    if response.lower() == "y":
        cmd = create_ip_routes(routes, version, vrf=vrf, prefix="no")

        return configure(cmd)
    def message(self, pubnub, message):
        output_message = ''
        new_message = message.message
        print("\nNew message received: ")
        utils.pprint(new_message)
        device = new_message['device']
        if device == DEVICE_HOSTNAME or device == "all":
            command_type = new_message['command_type']
            incident = new_message['incident']

            # execute the configuration type of commands
            if command_type == 'config':
                try:
                    # parse the config commands or command
                    command = new_message['commands']
                    command_list = command.split('!')
                    comment = 'Configuration commands received: ' + command

                    # print to Python console, log to host device, and update ServiceNow
                    print(comment)
                    execute('send log WhatsOp:   ' + comment)
                    service_now_apis.update_incident(incident, comment, SNOW_DEV)

                    # submit the command using Python CLI, update incident with result
                    output = configure(command_list)
                    output_message = (str(output).replace('),', '),\n')).replace('[', ' ').replace(']', ' ')
                    print(output_message)
                    service_now_apis.update_incident(incident, output_message, SNOW_DEV)
                    status_message = 'Configuration command Successful'
                except:
                    status_message = "Configuration Command Executed"
            print(output_message)

            # execute the exec type of commands
            if command_type == 'exec':
                try:

                    # parse the exec command
                    command = new_message['commands']
                    comment = str('Exec command received: ' + command)

                    # print to Python console, log to host device, and update ServiceNow
                    print(comment)
                    execute('send log WhatsOp:   ' + comment)
                    service_now_apis.update_incident(incident, comment, SNOW_DEV)

                    # send the command to device using Python CLI
                    output_message = execute(str(command))
                    service_now_apis.update_incident(incident, output_message, SNOW_DEV)

                    # pretty print the command output to console
                    out_list = output_message.split('\n')
                    for items in out_list:
                        if items is not "":
                            print(items)
                    status_message = 'Successful'
                except:
                    status_message = 'Unsuccessful'

            print(str('\nCommand result:  ' + status_message))
예제 #18
0
def shutdown(save=False, abnormal=False):
    """ Cleansup and saves config if needed and terminates script """
    if save:
        log(6, 'Saving configuration upon script termination')

    # store script state to LOGAPI if specified
    upload(status='Failed' if abnormal else 'Finished')

    if SYSLOG:
        cli.configure('''no logging host %s
            no logging discriminator ztp''' % SYSLOG)

    if save:
        cli.execute('copy running-config startup-config')

    # terminate script with exit status
    sys.exit(int(abnormal))
예제 #19
0
def install(target, is_chassis):
    """ Returns True if install script is configured or False otherwise """
    # remove leading zeros from required version numbers and compare
    if (target.version is None or target.install is None
            or ztp['version'] == re.sub(r'\b0+(\d)', r'\1',
                                        target.version.strip())):
        return False

    install_url = urljoin(target.base_url, target.install)
    # terminate script in case of invalid file
    log(6, 'Checking %s' % install_url)
    if not is_iosxe_package(install_url):
        log(3, '%s is not valid image file' % install_url)
        shutdown(save=False, abnormal=True)

    # change boot mode if device is in bundle mode
    if 'bundle' in ztp['version']:
        fs = 'bootflash:' if is_chassis else 'flash:'
        log(6, 'Changing the Boot Mode')
        cli.configure('''no boot system
            boot system {}packages.conf'''.format(fs))
        cli.execute('write memory')
        cli.execute('write erase')
        # install command needs confirmation on changed boot config
        confirm_bm = '''pattern "\[y\/n\]|#"
            action 5.3 cli command "y"'''
    else:
        confirm_bm = ''

    # Configure EEM applet for interactive command execution
    cli.configure('''event manager applet upgrade
        event none maxrun 900
        action 1.0 cli command "enable"
        action 2.0 syslog msg "Removing inactive images..."
        action 3.0 cli command "install remove inactive" pattern "\[y\/n\]|#"
        action 3.1 cli command "y"
        action 4.0 syslog msg "Downloading and installing image..."
        action 5.0 cli command "install add file %s activate commit" pattern "\[y\/n\/q\]|#"
        action 5.1 cli command "n" pattern "\[y\/n\]|#"
        action 5.2 cli command "y" %s
        action 6.0 syslog msg "Reloading stack..."
        action 7.0 reload''' % (install_url, confirm_bm))
    return True
예제 #20
0
def deploy_eem_cleanup_script():
    install_command = 'install remove inactive'
    eem_commands = ['event manager applet cleanup',
                    'event none maxrun 600',
                    'action 1.0 cli command "enable"',
                    'action 2.0 cli command "%s" pattern "\[y\/n\]"' % install_command,
                    'action 2.1 cli command "y" pattern "proceed"',
                    'action 2.2 cli command "y"'
                    ]
    results = configure(eem_commands)
    print '\n*** Successfully configured cleanup EEM script on device! ***'
예제 #21
0
def deploy_eem_upgrade_script(image):
    install_command = 'install add file flash:' + image + ' activate commit'
    eem_commands = ['event manager applet upgrade',
                    'event none maxrun 600',
                    'action 1.0 cli command "enable"',
                    'action 2.0 cli command "%s" pattern "\[y\/n\/q\]"' % install_command,
                    'action 2.1 cli command "n" pattern "proceed"',
                    'action 2.2 cli command "y"'
                    ]
    results = configure(eem_commands)
    print '\n*** Successfully configured upgrade EEM script on device! ***'
예제 #22
0
def file_transfer(tftp_server, file, file_system='flash:/'):
    destination = file_system + file
    # Set commands to prepare for file transfer
    commands = ['file prompt quiet', 'ip tftp blocksize 8192']
    results = configure(commands)
    print '*** Successfully set "file prompt quiet" on switch ***'
    transfer_file = "copy tftp://%s/%s %s vrf Mgmt-vrf" % (tftp_server, file,
                                                           destination)
    print 'Transferring %s to %s' % (file, file_system)
    transfer_results = cli(transfer_file)
    if 'OK' in transfer_results:
        print '*** %s was transferred successfully!!! ***' % (file)
    elif 'XXX Error opening XXX' in transfer_results:
        raise ValueError("XXX Failed Xfer XXX")
예제 #23
0
def reschedule(seconds, *args):
    '''
    set an EEM countdown timer to run the script again
    :param seconds:
    :param *args: the initial args that were passed to the script
    :return:
    '''
    UPDATE_SCRIPT_FIRING_COMMANDS = """
event manager applet DNS_update
    event timer countdown time %s
    action 1.0 cli command "enable"
    action 1.1 cli command "guestshell run python %s
"""
    responses = configure(UPDATE_SCRIPT_FIRING_COMMANDS % (seconds, " ".join(args)))
    success = reduce(lambda x, y: x and y, [r.success for r in responses])
    status = "Success" if success else "Fail"
    log("reschedule in : %s seconds: status: %s" % (str(seconds), status), 5)
예제 #24
0
파일: ztp.py 프로젝트: boclay/IOS-XE-ZTP
def configure_network(**kwargs):
    # Display results and configure the device with returned attributes
    if 'ip' in kwargs and kwargs['ip'] is not None:
        print '\nZTP-provisioned hostname:      {}'.format(kwargs['hostname'])
        print 'ZTP-provisioned IP address:    {}'.format(kwargs['ip'])
        print '\n****************************************\n\n'
        configure(['hostname {}'.format(kwargs['hostname'])])
        configure([
            'int g0/0', 'ip address {} {}'.format(kwargs['ip'],
                                                  kwargs['netmask'])
        ])
        configure(
            ['ip route vrf Mgmt-vrf 0.0.0.0 0.0.0.0 {}'.format(kwargs['gw'])])
예제 #25
0
def add_acl(ip):
    '''
    add an entry to the ACL.  look at success or not of the commands
    :param ip:
    :return:
    '''
    UPDATE_ACL_COMMANDS = """
ip access-list extended %s
no deny ip any any
remark %s
permit ip any host %s
deny ip any any
"""
    localtime = time.asctime(time.localtime(time.time()))
    remark = "Added %s @%s" % (ip, localtime)
    responses = configure(UPDATE_ACL_COMMANDS % (ACLNAME, remark, ip))
    success = reduce(lambda x, y: x and y, [r.success for r in responses])
    status = "Success" if success else "Fail"
    log("adding IP: %s to ACL: status: %s" % (ip, status), 5)
def configure(configuration):
    """Apply configuration to the device.

    Configure terminal is entered automatically.

    Examples:
        >>> configuration = '''interface lo0
             shutdown'''
        >>> configure(configuration)

    Args:
        configuration: string, configuration commands separated by \n

    Returns:
        string, output (if any) from applying configuration
    """
    if not is_debug_environment():
        import cli
        return cli.configure(configuration)
예제 #27
0
    def runTestConfigs(self, test_config):
        self.test_config = test_config
        self.commands = [r.command for r in test_config.results]

        if PRINT_TEST_CONFIGS:
            print()
            print("\n".join(self.commands))

        if self.use_string:
            commands_to_run = "\n".join(self.commands)
        else:
            commands_to_run = self.commands

        try:
            self.results = cli.configure(commands_to_run)
            if any([not r.success for r in self.test_config.results]):
                self.fail(
                    "cli.configure should raise an exception if there are any problems with the result."
                )
        except cli.CLIConfigurationError as e:
            self.results = e.commands
예제 #28
0
from config import FOLDER_NAME

import os

os.chdir(FOLDER_NAME)

# This code is needed to run after every change made to the configuration of the switch

# check if 'Config_Files' folder exists and creates one if it does not

if not os.path.exists('Config_Files'):
    os.makedirs('Config_Files')

    # add additional vty lines, two required for EEM
    configure(
        'no ip http active-session-modules none ; line vty 0 15 ; length 0 ; transport input ssh ; exit'
    )

    print('Created additional vty lines')

    f = open('vasi_config.txt', 'r')
    cli_commands = f.read()
    configure(cli_commands)
    f.close()

    print('Configured VASI interfaces, vrf R, Loopback111, and routing')

    f = open('monitor_route_applet.txt', 'r')
    cli_commands = f.read()
    configure(cli_commands)
    f.close()
import cli

service_internal = ["service internal"]
no_service_internal = ["no service internal"]
hiddencli_list = []
cli_list = []

x = raw_input('Please input exec command with ? >')
print "\n\n *** Hidden CLI Information - ### ", x  ," ### *** \n\n"

cli.configure(service_internal)
output_hidden = cli.execute(x)

for hidden in output_hidden.split("\n"):
    hiddencli_list.append(hidden.split(' ')[2])

cli.configure(no_service_internal)
output = cli.execute(x)

for cli in output.split("\n"):
    cli_list.append(cli.split(' ')[2])

hidden_option = list(set(hiddencli_list) - set(cli_list))

for ho in sorted(hidden_option):
    print ho

print "\n\n *************** \n\n" 
print "Number of Hidden Command in exec mode is :", len(hidden_option) 
print "\n\n *************** \n\n"
예제 #30
0
def base_config():
    configure(['hostname adam-ztd'])
    configure(['username {} privilege 15 password {}'.format(USER, PASSWORD)])
    configure(['enable secret {}'.format(ENABLE)])
    configure(['line vty 0 4', 'login local'])