Python 只读取文本文件中的最后一行 [英] Python reads only last line in text file

查看:94
本文介绍了Python 只读取文本文件中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to read 2 IP address from text file and connect these devices and run the "conf t" command on these devices. When i trying to do this job by following coding, python reads only last line in text file, not reading the first line. What should i do? Thanks.

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")

推荐答案

也许,您希望这样做?

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()

这篇关于Python 只读取文本文件中的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆