Example #1
0
def main():
    print('Interactive script to scp files to network devices with netmiko')
    print('--------')
    print('Chose direction of file transfer')
    print('1. From LOCAL to REMOTE')
    print('2. From REMOTE to LOCAL')
    transfer_direction = input()

    if transfer_direction == '1':
        direction = 'put'
        source_file = input('Source file name : ')
        dest_file = input('Destination file name : ')
        file_system = 'disk0:'

        ciscoasa = {
            'device_type': 'cisco_asa',
            'ip': '192.168.1.76',
            'username': '******',
            'password': os.getenv('ciscopass'),
        }

        ssh_conn = ConnectHandler(**ciscoasa)
        transfer_dict = file_transfer(ssh_conn,
                                      source_file=source_file,
                                      dest_file=dest_file,
                                      file_system=file_system,
                                      direction=direction,
                                      overwrite_file=True)

        print(transfer_dict)

    elif transfer_direction == '2':
        direction = 'get'
        dest_file = input('Destination file name on remote device : ')
        source_file = input('Source file : ')
        file_system = 'disk0:'

        ciscoasa = {
            'device_type': 'cisco_asa',
            'ip': '192.168.1.76',
            'username': '******',
            'password': os.getenv('ciscopass'),
        }

        ssh_conn = ConnectHandler(**ciscoasa)
        transfer_dict = file_transfer(ssh_conn,
                                      source_file=source_file,
                                      dest_file=dest_file,
                                      file_system=file_system,
                                      direction=direction,
                                      overwrite_file=True)

        print(transfer_dict)
Example #2
0
def netmiko_file_transfer(task, source_file, dest_file, **kwargs):
    """
    Execute Netmiko file_transfer method

    Arguments:
        source_file(str): Source file.
        dest_file(str): Destination file.
        kwargs (dict, optional): Additional arguments to pass to file_transfer

    Returns:
        :obj:`nornir.core.task.Result`:
          * result (``bool``): file exists and MD5 is valid
          * changed (``bool``): the destination file was changed

    """
    net_connect = task.host.get_connection("netmiko")
    kwargs.setdefault("direction", "put")
    scp_result = file_transfer(net_connect,
                               source_file=source_file,
                               dest_file=dest_file,
                               **kwargs)
    if kwargs.get("disable_md5") is True:
        file_valid = scp_result["file_exists"]
    else:
        file_valid = scp_result["file_exists"] and scp_result["file_verified"]
    return Result(host=task.host,
                  result=file_valid,
                  changed=scp_result["file_transferred"])
Example #3
0
def transfer_file(connection, source_file, dest_file):
    '''
    Transfers a file to a device
    @args:
        - connection - config to connect to a device
        - source_file - source location of the file
        - dest_file - name of the file on the device
    '''
    try:

        session = netmiko.ConnectHandler(**connection)
        session.enable()
        file_system = 'bootflash:'
        if 'cs' in connection['ip']:
            file_system = 'flash:'

        if 'cr' in node:
            show_rommon_version(connection)

        my_transfer = file_transfer(
            session,
            source_file = f'{source_file}',
            dest_file = f'{dest_file}',
            file_system = f'{file_system}'
        )

        session.disconnect()


    except Exception as e:
        log(f'transfer_file() Error -> {str(e)}')
        print(f'exception in transfer_file : {e}')
def netmiko_file_transfer(task: Task, source_file: str, dest_file: str,
                          **kwargs: Any) -> Result:
    """
    Execute Netmiko file_transfer method

    Arguments:
        source_file: Source file.
        dest_file: Destination file.
        kwargs: Additional arguments to pass to file_transfer

    Returns:
        Result object with the following attributes set:
          * result (``bool``): file exists and MD5 is valid
          * changed (``bool``): the destination file was changed

    """
    net_connect = task.host.get_connection("netmiko", task.nornir.config)
    kwargs.setdefault("direction", "put")
    scp_result = file_transfer(net_connect,
                               source_file=source_file,
                               dest_file=dest_file,
                               **kwargs)
    if kwargs.get("disable_md5") is True:
        file_valid = scp_result["file_exists"]
    else:
        file_valid = scp_result["file_exists"] and scp_result["file_verified"]
    return Result(host=task.host,
                  result=file_valid,
                  changed=scp_result["file_transferred"])
def scp_file(net_device):
    # Make a copy of the dictionary since we modify it
    device_dict = net_device.copy()
    file_system = device_dict.pop('file_system')

    # Create the Netmiko SSH connection
    ssh_conn = ConnectHandler(**device_dict)

    # Transfer the IOS image to device
    source_file = "my_file.txt"
    dest_file = "my_file.txt"

    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        file_system=file_system,
        direction='put',
        overwrite_file=False,
    )

    md5_check = transfer_dict['file_verified']
    file_exists = transfer_dict['file_exists']

    if md5_check and file_exists:
        print("File successfully transferred to: {host}".format(**net_device))
    else:
        print("Failure on SCP: {host} !!!".format(**net_device))

    ssh_conn.disconnect()
def transfer_file(a_device):

    source_file = 'my_file4.txt'
    dest_file = 'transfered_file4.txt'
    direction = 'put'

    file_system = a_device.pop('file_system')

    # Create the Netmiko SSH connection
    ssh_conn = ConnectHandler(**a_device)
    transfer_dict = file_transfer(ssh_conn,
                                  source_file=source_file,
                                  dest_file=dest_file,
                                  file_system=file_system,
                                  direction=direction,
                                  overwrite_file=True)
    print("Transfer_dict for {}:  {}".format(a_device['host'], transfer_dict))

    if transfer_dict['file_verified'] == True:
        print(
            "The MD5 Hash has been verfied.  The file transfer was successful!"
        )
    else:
        print(
            "The MD5 Hash could not be verfied.  The file transfer was NOT successful!  Please try again"
        )
Example #7
0
def main():
    device_connection = Netmiko(**device)


    # Had to add the following to users ssh config file ~/.ssh/config:
    #
    #    Host ios-xe-mgmt.cisco.com
    #    KexAlgorithms=+diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
    #
    # otherwise the connection would fail due to no matching key exchanged method found.

    cli_output = device_connection.send_config_set(configuration)

    print(cli_output)

    # Transfer ZTP script file
    transfer_dict = file_transfer(device_connection,
                                    source_file=source, dest_file=destination,
                                      file_system='bootflash:',
                                        direction='put',
                                          overwrite_file=True)
    
    print(transfer_dict)

    device_connection.disconnect()
def upload_nemiko(net_device):
    print("Upload on:", HOST)
    # Create the Netmiko SSH connection
    try:
        ssh_conn = ConnectHandler(**net_device)
        transfer_dict = {}
        transfer_dict = file_transfer(
            ssh_conn,
            source_file=SOURCE_FILE,
            dest_file=SOURCE_FILE,
        )
        print(80 * "=")
        print('Results for', HOST + ':')
        print('File exists already: ', transfer_dict['file_exists'])
        print('File transferred: ', transfer_dict['file_transferred'])
        print('MD5 verified :', transfer_dict['file_verified'])
    except NetMikoTimeoutException:
        print(80 * "=")
        print('Results for', HOST + ':')
        print('Skipped: SSH Timed out')
        #continue
    except (AuthenticationException, NetMikoAuthenticationException):
        print(80 * "=")
        print('Results for', HOST + ':')
        print('Skipped: Authentication failed')
Example #9
0
    def load_replace_candidate(self, filename=None, config=None):

        if not filename and not config:
            raise ReplaceConfigException('filename or config parameter must be provided.')

        if not filename:
            tmp_file = self._create_tmp_file(config)
            filename = tmp_file
        else:
            if not os.path.isfile(filename):
                raise ReplaceConfigException("File {} not found".format(filename))

        try:
            transfer_result = file_transfer(
                self._netmiko_device,
                source_file=filename,
                dest_file=self.candidate_cfg,
                file_system=self._dest_file_system,
                direction="put",
                overwrite_file=True,
            )
            if not transfer_result['file_exists']:
                raise ValueError()
        except Exception:
            msg = ('Could not transfer file. There was an error '
                   'during transfer. Please make sure remote '
                   'permissions are set.')
            raise ReplaceConfigException(msg)

        self.replace = True
        self.loaded = True
        if config and os.path.isfile(tmp_file):
            os.remove(tmp_file)
Example #10
0
 def job(self, args):
     task, node, results = args
     try:
         netmiko_handler = ConnectHandler(
             device_type=self.driver,
             ip=node.ip_address,
             username=task.user.name,
             password=cisco_type7.decode(task.user.password),
             secret=node.secret_password
         )
         transfer_dict = file_transfer(
             netmiko_handler,
             source_file=self.source_file,
             dest_file=self.dest_file,
             file_system=self.file_system,
             direction=self.direction,
             overwrite_file=self.overwrite_file,
             disable_md5=self.disable_md5,
             inline_transfer=self.inline_transfer
         )
         result = str(transfer_dict)
         success = True
         netmiko_handler.disconnect()
     except Exception as e:
         result = 'netmiko config did not work because of {}'.format(e)
         success = False
     results[node.name] = result
     return success
Example #11
0
def main():

    filename = 'devices.yml'
    my_devices = read_yaml(filename)

    for hostname, net_device in my_devices.items():
        file_system = net_device.pop('file_system')
        net_device['password'] = '******'

        ssh_conn = ConnectHandler(**net_device)
        print(ssh_conn.find_prompt())

        source_file = "my_file.txt"
        dest_file = "my_file.txt"

        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            file_system=file_system,
            direction='put',
            overwrite_file=False,
        )

        md5_check = transfer_dict['file_verified']
        file_exists = transfer_dict['file_exists']

        if md5_check and file_exists:
            print("File successfully transferred to: {host}".format(
                **net_device))
        else:
            print("Failure on SCP: {host} !!!".format(**net_device))
        print()
Example #12
0
def main():
    hostnames = [
        'arista1.twb-tech.com',
        'arista2.twb-tech.com',
        'arista3.twb-tech.com',
        'arista4.twb-tech.com',
    ]

    for host in hostnames:
        net_device = device_dictionary(host)
        file_system = net_device.pop('file_system')
        ssh_conn = ConnectHandler(**net_device)
        print(ssh_conn.find_prompt())

        source_file = "my_file.txt"
        dest_file = "my_file.txt"

        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            file_system=file_system,
            direction='put',
            overwrite_file=False,
        )

        md5_check = transfer_dict['file_verified']
        file_exists = transfer_dict['file_exists']

        if md5_check and file_exists:
            print("File successfully transferred to: {host}".format(
                **net_device))
        else:
            print("Failure on SCP: {host} !!!".format(**net_device))
        print()
Example #13
0
def main():
	password = getpass()

	net_devices = []

	# USE FOR PYNET AWS LAB
	# with open("net_devices.yaml", 'r') as f:
	# 	try:
	# 		net_devices = yaml.load(f)
	# 	except yaml.YAMLError as exc:
	# 		print(exc)

	## USE FOR LOCAL LAB USE
	with open("local_net_devices.yaml", 'r') as f:
		try:
			net_devices = yaml.load(f)
		except yaml.YAMLError as exc:
			print(exc)


	## THSOOT
	# pprint(net_devices)
	# pprint(type(net_devices))


	source_file = 'my_file4.txt'
	dest_file = 'transfered_file4.txt'
	direction = 'put'

	for net_device in net_devices:

		net_device['password'] = password
		file_system = net_device.pop('file_system')  
		pprint(net_device)

	    #TSHOOT
	    # pprint(net_device)
	    # pprint(type(net_device))
	    # pprint(net_device['password'])


	    # Create the Netmiko SSH connection
		ssh_conn = ConnectHandler(**net_device)
		transfer_dict = file_transfer(ssh_conn,
	                                  source_file=source_file, 
	                                  dest_file=dest_file,
	                                  file_system=file_system, 
	                                  direction=direction,
	                                  overwrite_file=True)
		print("Transfer_dict for {}:  {}".format(net_device['host'],transfer_dict))

		if transfer_dict['file_verified']==True:
			print("The MDF has been verfied.  The file transfer was successful!")
		else:
			print("The MDF could not be verfied.  The file transfer was NOT successful!  Please try again")
Example #14
0
 def job(self, device, _):
     netmiko_handler = self.netmiko_connection(device)
     transfer_dict = file_transfer(netmiko_handler,
                                   source_file=self.source_file,
                                   dest_file=self.dest_file,
                                   file_system=self.file_system,
                                   direction=self.direction,
                                   overwrite_file=self.overwrite_file,
                                   disable_md5=self.disable_md5,
                                   inline_transfer=self.inline_transfer)
     netmiko_handler.disconnect()
     return {'success': True, 'result': transfer_dict}
Example #15
0
 def job(self, payload: dict, device: Device) -> dict:
     netmiko_handler = self.netmiko_connection(device)
     transfer_dict = file_transfer(
         netmiko_handler,
         source_file=self.source_file,
         dest_file=self.dest_file,
         file_system=self.file_system,
         direction=self.direction,
         overwrite_file=self.overwrite_file,
         disable_md5=self.disable_md5,
         inline_transfer=self.inline_transfer,
     )
     netmiko_handler.disconnect()
     return {"success": True, "result": transfer_dict}
def code_upload(ip, device_details, output_q):
    output_dict = {}
    hostname = ip
    device_details.update({'ip': ip})
    connection = ConnectHandler(**device_details)
    print('starting file transfer to device: ' + ip)
    transfer_result = file_transfer(connection,
                                    source_file=source_file,
                                    dest_file=dest_file,
                                    file_system=file_system,
                                    direction=direction,
                                    overwrite_file=True)
    output_dict[hostname] = transfer_result
    output_q.put(output_dict)
Example #17
0
def main(argv):
    """
    Execution starts here.
    """

    # Read host file into structured data, may raise YAMLerror.
    #
    #
    with open("host.yml", "r") as handle:
        host_root = safe_load(handle)

    # Netmiko uses "cisco_ios" instead of "ios"  AND
    # "cisco_xr" instead of "iosxr", so use a mapping dict to convert
    # "cisco_nxos" instead of "nxos"
    platform_map = {"ios": "cisco_ios", "nxos": "cisco_nxos"}

    # Iterate over the list of hosts (list of dictionaries)
    for host in host_root["host_list"]:

        # uset the map to get the poper netmiko paltform
        platform = platform_map[host["platform"]]

        # Create a netmiko SSH connection handler to access the device:
        # Initialie ssh connection
        print(f"Connecting to {host['name']}")
        conn = Netmiko(
            host=host["name"],
            username="******",
            password="******",
            device_type=platform,
        )

        # Upload the file specified. the dict.get(key) function dictionaries
        # to  retrieve the value at the specified key and returns Environment
        # if it does not exist. Very usefule for network automtions!
        print(f" Uploading {argv[1]}")
        result = file_transfer(
            conn,
            source_file=argv[1],
            dest_file=argv[1],
            file_system=host.get("file_system"),
        )

        # Print result details
        print(f" Details: {result}\n")

        # close session when we are done..
        conn.disconnect()
Example #18
0
 def job(self, run: "Run", payload: dict, device: Device) -> dict:
     netmiko_connection = run.netmiko_connection(device)
     source = run.sub(run.source_file, locals())
     destination = run.sub(run.destination_file, locals())
     run.log("info", f"Transferring file {source} on {device.name}")
     transfer_dict = file_transfer(
         netmiko_connection,
         source_file=source,
         dest_file=destination,
         file_system=run.file_system,
         direction=run.direction,
         overwrite_file=run.overwrite_file,
         disable_md5=run.disable_md5,
         inline_transfer=run.inline_transfer,
     )
     return {"success": True, "result": transfer_dict}
Example #19
0
 def job(self, task, device, results, payloads):
     try:
         netmiko_handler = netmiko_connection(self, device)
         transfer_dict = file_transfer(netmiko_handler,
                                       source_file=self.source_file,
                                       dest_file=self.dest_file,
                                       file_system=self.file_system,
                                       direction=self.direction,
                                       overwrite_file=self.overwrite_file,
                                       disable_md5=self.disable_md5,
                                       inline_transfer=self.inline_transfer)
         result = transfer_dict
         success = True
         netmiko_handler.disconnect()
     except Exception as e:
         result = f'netmiko config did not work because of {e}'
         success = False
     return success, result, result
Example #20
0
def main(argv):
    """
    Execution starts here.
    """

    # Read the hosts file into structured data, may raise YAMLError
    with open("hosts.yml", "r") as handle:
        host_root = safe_load(handle)

    # Netmiko uses "cisco_ios" instead of "ios" and
    # "cisco_xr" instead of "iosxr", so use a mapping dict to convert
    platform_map = {"ios": "cisco_ios", "iosxr": "cisco_xr"}

    # Iterate over the list of hosts (list of dictionaries)
    for host in host_root["host_list"]:

        # Use the map to get the proper Netmiko platform
        platform = platform_map[host["platform"]]

        # Initialize the SSH connection
        print(f"Connecting to {host['name']}")
        conn = Netmiko(
            host=host["name"],
            username="******",
            password="******",
            device_type=platform,
        )

        # Upload the file specified. The dict.get(key) function tries
        # to retrieve the value at the specified key and returns None
        # if it does not exist. Very useful in network automation!
        print(f"  Uploading {argv[1]}")
        result = file_transfer(
            conn,
            source_file=argv[1],
            dest_file=argv[1],
            file_system=host.get("file_system"),
        )

        # Print the resulting details
        print(f"  Details: {result}\n")
        conn.disconnect()
Example #21
0
 def job(self,
         payload: dict,
         device: Device,
         parent: Optional[Job] = None) -> dict:
     netmiko_connection = self.netmiko_connection(device, parent)
     self.logs.append(
         "Transferring file {self.source_file} on {device.name}")
     source = self.sub(self.source_file, locals())
     destination = self.sub(self.destination_file, locals())
     transfer_dict = file_transfer(
         netmiko_connection,
         source_file=source,
         dest_file=destination,
         file_system=self.file_system,
         direction=self.direction,
         overwrite_file=self.overwrite_file,
         disable_md5=self.disable_md5,
         inline_transfer=self.inline_transfer,
     )
     return {"success": True, "result": transfer_dict}
Example #22
0
def code_upload(devicedict, image_file, output_q):
    output_dict = {}
    hostname = devicedict['host']
    file_system = devicedict.pop('file_system')
    connection = ConnectHandler(**devicedict)
    print('starting file transfer to device: ' + hostname)
    transfer_result = file_transfer(connection,
                                    source_file=image_file,
                                    dest_file=image_file.strip('./images/'),
                                    file_system=file_system,
                                    direction='put',
                                    overwrite_file=True)
    boot_config = 'boot system {}:{}'.format(file_system,
                                             image_file.strip('./images/'))

    connection.config_mode()
    config_output = connection.send_command(boot_config)
    config_output += connection.send_command_expect('write mem')

    output_dict[hostname] = transfer_result
    output_dict[hostname]['config'] = config_output
    output_q.put(output_dict)
Example #23
0
def main(argv):
    """
    Inventory: IOS v15 cisco ios
    """
    # Reads hosts.yml files into structured data, may raise YAMLError
    with open("hosts.yml", "r") as host_file:
        host_list = safe_load(host_file)

    platform_map = {"ios": "cisco_ios", "iosxr": "cisco_xr"}

    # recorremos la lista de dispositivos del diccionario
    for host in host_list["host_list"]:

        platform = platform_map[host["platform"]]

        # Create netmiko instance
        conn = Netmiko(
            ip=host["ip"],
            port=22,
            username="******",
            password="******",
            device_type=platform,
            # secret="cisco",
            # global_delay_factor=2,
        )
        print(f"Entramos exitosamente a {conn.find_prompt()}")
        print(f" Uploading {argv[1]}...")
        result = file_transfer(
            conn,
            source_file=argv[1],
            dest_file=argv[1],
            file_system=host.get("file_system"),
            # la funcion get va a tratar de buscar el key file_systme
            # si no lo logra devuleve None
            # dsocket_timeout=10.0,
        )

        print(f" Details: {result}\n")
        conn.disconnect()
Example #24
0
from netmiko import ConnectHandler, file_transfer
from getpass import getpass

device1 = {
    "host": 'cisco3.lasthop.io',
    "username": '******',
    "password": getpass(),
    "device_type": 'cisco_ios',
    #session_log = 'my_session.txt'
}

source_file = "text_kigun.txt"
dest_file = "testx.txt"
direction = "put"
file_system = "bootflash:"

# create the netmiko ssh conenction
ssh_conn = ConnectHandler(**device1)
transfer_dict = file_transfer(
    ssh_conn,
    source_file=source_file,
    dest_file=dest_file,
    file_system=file_system,
    direction=direction,
    overwrite_file=True,
)
print(transfer_dict)
ssh_conn.disconnect()
def test_file_transfer(scp_file_transfer):
    """Test Netmiko file_transfer function."""
    ssh_conn, file_system = scp_file_transfer
    platform = ssh_conn.device_type
    source_file = f"test_{platform}/test9.txt"
    dest_file = "test9.txt"
    direction = "put"

    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )

    # No file on device at the beginning
    assert (
        transfer_dict["file_exists"]
        and transfer_dict["file_transferred"]
        and transfer_dict["file_verified"]
    )

    # File exists on device at this point
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    assert (
        transfer_dict["file_exists"]
        and not transfer_dict["file_transferred"]
        and transfer_dict["file_verified"]
    )

    # Don't allow a file overwrite (switch the source file, but same dest file name)
    source_file = f"test_{platform}/test2_src.txt"
    with pytest.raises(Exception):
        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            file_system=file_system,
            direction=direction,
            overwrite_file=False,
        )

    # Don't allow MD5 and file overwrite not allowed
    source_file = f"test_{platform}/test9.txt"
    with pytest.raises(Exception):
        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            disable_md5=True,
            file_system=file_system,
            direction=direction,
            overwrite_file=False,
        )

    # Don't allow MD5 (this will force a re-transfer)
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        disable_md5=True,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    assert (
        transfer_dict["file_exists"]
        and transfer_dict["file_transferred"]
        and not transfer_dict["file_verified"]
    )

    # Transfer 'test2.txt' in preparation for get operations
    source_file = "test2_src.txt"
    dest_file = "test2.txt"
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    assert transfer_dict["file_exists"]

    # GET Operations
    direction = "get"
    source_file = "test9.txt"
    dest_file = f"test_{platform}/testx.txt"
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        disable_md5=False,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    # File get should occur here
    assert (
        transfer_dict["file_exists"]
        and transfer_dict["file_transferred"]
        and transfer_dict["file_verified"]
    )

    # File should exist now
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        disable_md5=False,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    assert (
        transfer_dict["file_exists"]
        and not transfer_dict["file_transferred"]
        and transfer_dict["file_verified"]
    )

    # Don't allow a file overwrite (switch the file, but same dest file name)
    source_file = f"test_{platform}/test2.txt"
    dest_file = f"test_{platform}/testx.txt"
    with pytest.raises(Exception):
        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            file_system=file_system,
            direction=direction,
            overwrite_file=False,
        )

    # Don't allow MD5 and file overwrite not allowed
    source_file = "test9.txt"
    dest_file = f"test_{platform}/testx.txt"
    with pytest.raises(Exception):
        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            disable_md5=True,
            file_system=file_system,
            direction=direction,
            overwrite_file=False,
        )

    # Don't allow MD5 (this will force a re-transfer)
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        disable_md5=True,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    assert (
        transfer_dict["file_exists"]
        and transfer_dict["file_transferred"]
        and not transfer_dict["file_verified"]
    )
Example #26
0
def test_file_transfer(scp_file_transfer):
    """Test Netmiko file_transfer function."""
    ssh_conn, file_system = scp_file_transfer
    source_file = 'test9.txt'
    dest_file = 'test9.txt'
    direction = 'put'
    print(file_system)

    transfer_dict = file_transfer(ssh_conn,
                                  source_file=source_file,
                                  dest_file=dest_file,
                                  file_system=file_system,
                                  direction=direction,
                                  overwrite_file=True)

    # No file on device at the beginning
    assert transfer_dict['file_exists'] and transfer_dict[
        'file_transferred'] and transfer_dict['file_verified']

    # File exists on device at this point
    transfer_dict = file_transfer(ssh_conn,
                                  source_file=source_file,
                                  dest_file=dest_file,
                                  file_system=file_system,
                                  direction=direction,
                                  overwrite_file=True)
    assert transfer_dict['file_exists'] and not transfer_dict[
        'file_transferred'] and transfer_dict['file_verified']

    # Don't allow a file overwrite (switch the source file, but same dest file name)
    source_file = 'test2_src.txt'
    with pytest.raises(Exception):
        transfer_dict = file_transfer(ssh_conn,
                                      source_file=source_file,
                                      dest_file=dest_file,
                                      file_system=file_system,
                                      direction=direction,
                                      overwrite_file=False)

    # Don't allow MD5 and file overwrite not allowed
    source_file = 'test9.txt'
    with pytest.raises(Exception):
        transfer_dict = file_transfer(ssh_conn,
                                      source_file=source_file,
                                      dest_file=dest_file,
                                      disable_md5=True,
                                      file_system=file_system,
                                      direction=direction,
                                      overwrite_file=False)

    # Don't allow MD5 (this will force a re-transfer)
    transfer_dict = file_transfer(ssh_conn,
                                  source_file=source_file,
                                  dest_file=dest_file,
                                  disable_md5=True,
                                  file_system=file_system,
                                  direction=direction,
                                  overwrite_file=True)
    assert transfer_dict['file_exists'] and transfer_dict[
        'file_transferred'] and not transfer_dict['file_verified']

    # Transfer 'test2.txt' in preparation for get operations
    source_file = 'test2_src.txt'
    dest_file = 'test2.txt'
    transfer_dict = file_transfer(ssh_conn,
                                  source_file=source_file,
                                  dest_file=dest_file,
                                  file_system=file_system,
                                  direction=direction,
                                  overwrite_file=True)
    assert transfer_dict['file_exists']

    # GET Operations
    direction = 'get'
    source_file = 'test9.txt'
    dest_file = 'testx.txt'
    transfer_dict = file_transfer(ssh_conn,
                                  source_file=source_file,
                                  dest_file=dest_file,
                                  disable_md5=False,
                                  file_system=file_system,
                                  direction=direction,
                                  overwrite_file=True)
    # File get should occur here
    assert transfer_dict['file_exists'] and transfer_dict[
        'file_transferred'] and transfer_dict['file_verified']

    # File should exist now
    transfer_dict = file_transfer(ssh_conn,
                                  source_file=source_file,
                                  dest_file=dest_file,
                                  disable_md5=False,
                                  file_system=file_system,
                                  direction=direction,
                                  overwrite_file=True)
    assert transfer_dict['file_exists'] and not transfer_dict[
        'file_transferred'] and transfer_dict['file_verified']

    # Don't allow a file overwrite (switch the file, but same dest file name)
    source_file = 'test2.txt'
    dest_file = 'testx.txt'
    with pytest.raises(Exception):
        transfer_dict = file_transfer(ssh_conn,
                                      source_file=source_file,
                                      dest_file=dest_file,
                                      file_system=file_system,
                                      direction=direction,
                                      overwrite_file=False)

    # Don't allow MD5 and file overwrite not allowed
    source_file = 'test9.txt'
    dest_file = 'testx.txt'
    with pytest.raises(Exception):
        transfer_dict = file_transfer(ssh_conn,
                                      source_file=source_file,
                                      dest_file=dest_file,
                                      disable_md5=True,
                                      file_system=file_system,
                                      direction=direction,
                                      overwrite_file=False)

    # Don't allow MD5 (this will force a re-transfer)
    transfer_dict = file_transfer(ssh_conn,
                                  source_file=source_file,
                                  dest_file=dest_file,
                                  disable_md5=True,
                                  file_system=file_system,
                                  direction=direction,
                                  overwrite_file=True)
    assert transfer_dict['file_exists'] and transfer_dict[
        'file_transferred'] and not transfer_dict['file_verified']
from netmiko import ConnectHandler
from netmiko import file_transfer

cisco_device = {
    'device_type': 'cisco_ios',
    'ip': '10.1.1.10',
    'username': '******',
    'password': '******',
    'port': 22,
    'secret': 'cisco',
    'verbose': True
}

connection = ConnectHandler(**cisco_device)

transfer_output = file_transfer(connection,
                                source_file='ospf.txt',
                                dest_file='ospf1.txt',
                                file_system='disk0:',
                                direction='put',
                                overwrite_file=True)

print(transfer_output)

connection.disconnect()
Example #28
0
from netmiko import ConnectHandler
from netmiko import file_transfer

cisco_device = {
    'device_type': 'linux',
    'ip': 'ip address',
    'username': '******',
    'password': '******',
    'port': 22,
    'secret': 'sudo password',
    'verbose': True
}

connection = ConnectHandler(**cisco_device)

transfer_output = file_transfer(connection,
                                source_file='source.ttxt',
                                dest_file='new.txt',
                                file_system='file system',
                                direction='put',
                                overwrite_file=True)

print(transfer_output)

connection.disconnect()
Example #29
0
def test_file_transfer(scp_file_transfer):
    """Test Netmiko file_transfer function."""
    ssh_conn, file_system = scp_file_transfer
    source_file = "test9.txt"
    dest_file = "test9.txt"
    direction = "put"
    print(file_system)

    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )

    # No file on device at the beginning
    assert (
        transfer_dict["file_exists"]
        and transfer_dict["file_transferred"]
        and transfer_dict["file_verified"]
    )

    # File exists on device at this point
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    assert (
        transfer_dict["file_exists"]
        and not transfer_dict["file_transferred"]
        and transfer_dict["file_verified"]
    )

    # Don't allow a file overwrite (switch the source file, but same dest file name)
    source_file = "test2_src.txt"
    with pytest.raises(Exception):
        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            file_system=file_system,
            direction=direction,
            overwrite_file=False,
        )

    # Don't allow MD5 and file overwrite not allowed
    source_file = "test9.txt"
    with pytest.raises(Exception):
        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            disable_md5=True,
            file_system=file_system,
            direction=direction,
            overwrite_file=False,
        )

    # Don't allow MD5 (this will force a re-transfer)
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        disable_md5=True,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    assert (
        transfer_dict["file_exists"]
        and transfer_dict["file_transferred"]
        and not transfer_dict["file_verified"]
    )

    # Transfer 'test2.txt' in preparation for get operations
    source_file = "test2_src.txt"
    dest_file = "test2.txt"
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    assert transfer_dict["file_exists"]

    # GET Operations
    direction = "get"
    source_file = "test9.txt"
    dest_file = "testx.txt"
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        disable_md5=False,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    # File get should occur here
    assert (
        transfer_dict["file_exists"]
        and transfer_dict["file_transferred"]
        and transfer_dict["file_verified"]
    )

    # File should exist now
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        disable_md5=False,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    assert (
        transfer_dict["file_exists"]
        and not transfer_dict["file_transferred"]
        and transfer_dict["file_verified"]
    )

    # Don't allow a file overwrite (switch the file, but same dest file name)
    source_file = "test2.txt"
    dest_file = "testx.txt"
    with pytest.raises(Exception):
        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            file_system=file_system,
            direction=direction,
            overwrite_file=False,
        )

    # Don't allow MD5 and file overwrite not allowed
    source_file = "test9.txt"
    dest_file = "testx.txt"
    with pytest.raises(Exception):
        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            disable_md5=True,
            file_system=file_system,
            direction=direction,
            overwrite_file=False,
        )

    # Don't allow MD5 (this will force a re-transfer)
    transfer_dict = file_transfer(
        ssh_conn,
        source_file=source_file,
        dest_file=dest_file,
        disable_md5=True,
        file_system=file_system,
        direction=direction,
        overwrite_file=True,
    )
    assert (
        transfer_dict["file_exists"]
        and transfer_dict["file_transferred"]
        and not transfer_dict["file_verified"]
    )
Example #30
0
def install_certificate():
    source_file = 'cacert.pem'
    dest_file = 'cacert.pem'
    direction = 'put'
    file_system = 'bootflash:'
    ssh_conn = ConnectHandler(**cisco)
    response = file_transfer(ssh_conn,
                             source_file=source_file,
                             dest_file=dest_file,
                             file_system=file_system,
                             direction=direction,
                             disable_md5=True,
                             overwrite_file=False)
    print(response)
    response = ssh_conn.send_command(
        "request platform software sdwan root-cert-chain install bootflash:cacert.pem"
    )
    print(response)
    ssh_conn.disconnect()

    ssh = createClient('10.78.108.98', '22', 'prisaha22', '33prisaha')
    scp = SCPClient(ssh.get_transport())
    stdin, stdout, stderr = ssh.exec_command(
        'request platform software sdwan csr upload bootflash:nk26.csr')
    stdin.write('sdwan-blr-master' + '\n')
    stdin.write('sdwan-blr-master' + '\n')
    stdin.flush()
    print(stdout.readlines())
    ssh.close()
    del ssh, stdin, stdout, stderr

    ssh = createClient('10.78.108.98', '22', 'prisaha22', '33prisaha')
    scp = SCPClient(ssh.get_transport())
    scp.get('nk26.csr', 'nk26.csr')
    #print(stdout.readlines())
    ssh.close()
    del ssh

    ssh = createClient('10.65.126.165', '22', 'tester', 'v1ptela0212')
    scp = SCPClient(ssh.get_transport())
    scp.put('nk26.csr', '/home/tester/root_ca/nk26.csr')
    stdin, stdout, stderr = ssh.exec_command('cd /home/tester/root_ca')
    stdin, stdout, stderr = ssh.exec_command(
        'openssl ca -config openssl.cnf -in /home/tester/root_ca/nk26.csr -out /home/tester/root_ca/nk26.pem'
    )
    stdin.write('f3rrar1' + '\n')
    stdin.write('y' + '\n')
    stdin.write('y' + '\n')
    stdin.flush()
    print(stdout.readlines())
    scp.get('/home/tester/root_ca/nk26.pem', 'nk26.pem')
    ssh.close()
    del ssh, stdin, stdout, stderr

    time.sleep(5)

    source_file = 'nk26.pem'
    dest_file = 'nk26.pem'
    direction = 'put'
    file_system = 'bootflash:'
    ssh_conn = ConnectHandler(**cisco)
    response = file_transfer(ssh_conn,
                             source_file=source_file,
                             dest_file=dest_file,
                             file_system=file_system,
                             direction=direction,
                             disable_md5=True,
                             overwrite_file=False)
    print(response)
    response = ssh_conn.send_command(
        "request platform software sdwan certificate install bootflash:nk26.pem"
    )
    print(response)

    ssh_conn.disconnect()

    print(
        "----------------------------certificate installed successfully----------------------------------"
    )

    time.sleep(5)

    print(
        "-----------------------------------register device-----------------------------"
    )

    register_device()
Example #31
0
def main():
    cli_args = parse_cli()
    devicefile = cli_args.config
    inputfile = cli_args.input_file
    destfile = cli_args.dest_file
    jinja_template = cli_args.template
    rendered_config = cli_args.rendered_config

    # load device file
    with open(devicefile) as f:
        data = yaml.safe_load(f.read())
        device = data.get('controller')

    config_snippet = create_templates(jinja_template, data)
    with open(rendered_config, 'w') as f:
        f.write(config_snippet)

    # create a list of vlans based on the translated config to be created using netmiko
    pattern = r'^vlan\s\d+'
    vlans = []

    with open(inputfile) as f:
        lines = f.readlines()
        for line in lines:
            match = re.search(pattern, line)
            if match:
                vlan = match.group()
                vlans.append(vlan)

    # open SSH connection
    conn_details = {key:value for key, value in device.items() if key in NETMIKO_PARAMS}
    net_connect = ConnectHandler(**conn_details)

    # enable SCP on the controller
    net_connect.send_config_set(['ip scp server enable'])
    # configure vlans on the controller
    net_connect.send_config_set(vlans)

    # copy the configuration to flash
    print('Copying Translated_Config.cfg to flash')
    file_transfer(net_connect, source_file=rendered_config, dest_file=destfile)

    # copy the file in flash to the startup-config and accept the prompt
    try:
        print('Copying flash:Translated_Config.cfg to startup-config')
        output = net_connect.send_command_timing('copy flash:initial.cfg startup-config')
        if "filename" in output:
            output += net_connect.send_command_timing(
                "\n", strip_command=False, strip_prompt=False
            )
        else:
            print('Translated_Config.cfg copied to startup-config successfully')
    except ValueError as error:
        if 'already exists' in str(error):
            print('File already present in controller flash, please move or rename and run the script again')
        else:
            raise error

    reboot_device(net_connect)
    net_connect.disconnect()
    time.sleep(10)
    port = data.get('api_port')
    protocol = 'https' if port == 443 else 'http'
    url = f"{protocol}://{device['host']}"
    endpoint = data.get('check_endpoint', '/restconf/data/ietf-yang-library:modules-state')
    headers = {
        'content-type': 'application/yang-data+json',
        'accept': 'application/yang-data+json'
    }
    username = device.get('username')
    pw = device.get('password')
    auth = (username, pw)

    netconf_is_up = socket_check(ip=device['host'], port=830)

    nginx_is_up = http_check(
        url=f"{url}{endpoint}",
        headers=headers,
        auth=auth
    )

    if nginx_is_up and netconf_is_up:
        print('Data collection initiated')
        time.sleep(5)
        document()
    else:
        print('Device did not come up before timeout expired')
Example #32
0
#!/usr/bin/env python
from getpass import getpass
from netmiko import ConnectHandler, file_transfer

password = getpass()

cisco = {
    "device_type": "cisco_ios",
    "host": "cisco1.twb-tech.com",
    "username": "******",
    "password": password,
}

source_file = "test1.txt"
dest_file = "test1.txt"
direction = "put"
file_system = "flash:"

ssh_conn = ConnectHandler(**cisco)
transfer_dict = file_transfer(
    ssh_conn,
    source_file=source_file,
    dest_file=dest_file,
    file_system=file_system,
    direction=direction,
    overwrite_file=True,
)

print(transfer_dict)