I guess the demo below illustrates what you need
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
"""
Used requests instead of urllib and requests.head in order to not download the file to the host and retransfer to the network device.