在文本文件中使用特定行

Using Specific Lines in a text file

我正在编写一个脚本来检查网络设备上的存储 space。 然后它检查 space 是否可以容纳要加载到其上的特定大小的文件。 我想做的是有一个文本文件,其中列出了可以临时修改的不同文件大小。 然后,脚本将查看此文件中的特定行以查找与该任务相关的数据。

所以目前在脚本中,我定义了以下信息。

#Cisco IOS 2811 Data

new_ios_2811 = "c2800nm-ipvoice_ivs-mz.151-2.T1.bin"

new_ios_2811_size = "51707860"

new_ios_2811_md5 = "bf3e0811b5626534fd2e4b68cdd042df"

所以在这个例子中,我想在第二行替换文本文件中的“51707860”。 我如何将其调用到脚本中?

我想下面的演示说明了您的需求

import sys

import requests
from netmiko.ssh_dispatcher import ConnectHandler


def calc_size(url: str) -> int:
    r = requests.head(url, allow_redirects=True)
    return r.headers.get("Content-Length", -1)


device = {
    "device_type": "cisco_ios",
    "ip": "sandbox-iosxe-latest-1.cisco.com",
    "username": "developer",
    "password": "C1sco12345",
    "secret": "",
    "fast_cli": False,
}

new_ios_2811 = ""  # add IOS image url here
new_ios_2811_size = calc_size(url="https://python.org")  # gets IOS image size
# print(size, f"{'FILE SIZE':<40}: {int(size) / float(1 << 20):.2f} MB")
new_ios_2811_md5 = "bf3e0811b5626534fd2e4b68cdd042df"

with ConnectHandler(**device) as conn:
    print(f"Connected to {conn.host}")
    if not conn.check_enable_mode():
        conn.enable()
    content = conn.send_command(command_string="dir flash:", use_textfsm=True)

    print("Calculating available flash space...")
    for f in content:
        d = int(f["total_free"]) - int(new_ios_2811_size)
        if f["total_free"] <= new_ios_2811_size:
            raise SystemExit(
                f"Not enough free space available! Only {f['total_free']} (Need more {abs(d)})",
                file=sys.stderr,
            )

        print(
            f"You can upload the new IOS image safely. free size after upload {d}/{f['total_size']}"
        )

        break

    print("Uploading...")

    """
    Do the upload here (SCP/TFTP/FTP/SFTP)
    Example function
    status = upload_ios_image(image=new_ios_2811, md5=new_ios_2811_md5)
    where status checks if upload was successful and md5 hash was verified
    """

使用 requests 代替 urllibrequests.head 以便不将文件下载到主机并重新传输到网络设备。