首页 > 解决方案 > Python 只读取文本文件中的最后一行

问题描述

我正在尝试从文本文件中读取 2 个 IP 地址并连接这些设备并在这些设备上运行“conf t”命令。当我尝试通过遵循编码来完成这项工作时,python 只读取文本文件中的最后一行,而不是读取第一行。我应该怎么办?谢谢。

import paramiko

username = "xxxx"
password = "yyyy"

f = open("C:\\Users\0\Desktop\\deneme.txt")

for line in f:
  ip_address = line.strip()
  ssh_client = paramiko.SSHClient()
  ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh_client.connect(hostname=ip_address, username=username, password=password)

f.close()

print ("Successfull", ip_address)

remote_connection = ssh_client.invoke_shell()

remote_connection.send("conf t\n")

标签: pythonparamikocisco

解决方案


也许,你想那样做?

import paramiko

username = "xxxx"
password = "yyyy"

f = open("C:\\Users\0\Desktop\\deneme.txt")

for line in f:
  ip_address = line.strip()
  ssh_client = paramiko.SSHClient()
  ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh_client.connect(hostname=ip_address, username=username, password=password)
  print ("Successfull", ip_address)
  remote_connection = ssh_client.invoke_shell()
  remote_connection.send("conf t\n")

f.close()

推荐阅读