繁体   English   中英

在文本文件中使用特定行

[英]Using Specific Lines in a text file

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

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

#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”。 我如何将其调用到脚本中?

您可以使用 Python 中的标准os库自动获取文件大小。

我想下面的演示说明了你需要什么

import os
import sys

from netmiko.ssh_dispatcher import ConnectHandler

device = {
    "device_type": "cisco_ios",
    "ip": "",
    "username": "",
    "password": "",
    "secret": "",
    "fast_cli": False,
}

new_ios_2811 = r"c2800nm-ipvoice_ivs-mz.151-2.T1.bin"
new_ios_2811_size = os.path.getsize(new_ios_2811)  # gets size in bytes
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
    """

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM