使用 python 的 Netmiko 文件传输

Netmiko FileTransfer with python

我正在编写一个脚本,使用 netmiko FileTransfer 将一些文件传输到 Cisco IOS 设备。下面是我找到的实现此目的的代码。但是我似乎找不到 source_file 应该在哪里或如何指定文件在主机上的位置。如何指定从何处复制该文件?

dest_file_system = 'disk0:/'
source_file = 'test1.txt' # where should this file be live?
dest_file = 'test1.txt'

with FileTransfer(ssh_conn, source_file=source_file, dest_file=dest_file,
file_system=dest_file_system) as scp_transfer:

if not scp_transfer.check_file_exists():
   if not scp_transfer.verify_space_available():
      raise ValueError("Insufficient space available on remote device")

        print("\nTransferring file\n")
        scp_transfer.transfer_file()

如果您只是想通过名称调用源文件,那么从脚本的角度来看,源文件应该与脚本本身位于同一目录中。如果要将文件移动到新目录,脚本中的搜索路径是相对于脚本所在目录 运行 的。示例 1 - file_name.txt 与您的脚本位于同一目录中 在您的脚本中,只需调用文件 source = "file_name.txt"。示例 2 在包含脚本的当前目录中创建 test_folder 并将其命名为 test_folder 将 file_name.txt 移动到 test_folder 中。在您的脚本中,您的源变量不需要看起来像这样 source = "test_folder/file_name.txt"

希望到目前为止您已经找到了解决方案。如果没有,那么您也可以尝试 netmiko 文件传输功能。这将是一种更安全、更有效的方式。

试试下面的示例脚本。

from getpass import getpass
from netmiko import ConnectHandler, file_transfer

password = getpass()

cisco = {
    "device_type": "cisco_ios",
    "host": "cisco1.twb-tech.com",
    "username": "pyclass",
    "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)