Python reads only last line in text file

痞子三分冷 提交于 2021-02-05 12:30:46

问题


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

回答1:


Maybe, you wish to do that ?

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


来源:https://stackoverflow.com/questions/51322450/python-reads-only-last-line-in-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!