簡體   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