我正在做一个从多个交换机收集某些信息的项目。请记住我对python和编程的新手。 我想要做的是:有一个.txt文件,其中包含我的开关名称 然后循环遍历该列表,并运行一些命令,并保存输出。
到目前为止,我有以下内容,它适用于单个交换机。正如你在评论中看到的那样,我试图打开我的list.txt并循环遍历它,但我的程序因为它在列表中而无法工作(输出:['switchname-1'])我如何阅读我的列表.txt并将变量作为纯文本,例如。没有所有列表字符的switchname-1?
import sys
import telnetlib
import time
password = "password"
command = "show interface status"
##with open ("list.txt", "r") as devicelist:
## hostlist = []
## hostlist=devicelist.readlines()
## print(hostlist)
hostlist= [ ("switchname-1","",""),]
for host in hostlist:
cmd1 = "enable"
tn = telnetlib.Telnet(host[0])
time.sleep(2)
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
time.sleep(2)
tn.write(cmd1.encode('ascii') + b"\n")
time.sleep(2)
tn.write(password.encode('ascii') + b"\n")
time.sleep(2)
tn.write(command.encode('ascii') + b"\n")
time.sleep(2)
tn.write(b"\n")
time.sleep(2)
tn.write(b"\n")
time.sleep(2)
tn.write(b"exit\n")
lastpost = tn.read_all().decode('ascii')
op=open ("output.txt", "w")
op.write(lastpost)
print("writing to file")
op.close()
print(lastpost)
tn.close()
我也在试图弄清楚是否有某种方式只打印交换机的最后一个输出而不是发布整个telnet会话的lastpost = tn.read_all().decode('ascii')
?
答案 0 :(得分:1)
with open ("list.txt", "r") as devicelist:
hostlist = []
hostlist=devicelist.readlines()
for host in hostlist:
print host
print(hostlist)
但我认为写作函数会更好:
def host_list(file_name):
with open(file_name, "r") as devicelist:
yield devicelist.readline()
然后在下面的代码中执行:
for h in host_list("your_file"):
...
该函数将一次读取一行文件并返回(产生)文本。
答案 1 :(得分:1)
工作代码:
import sys
import telnetlib
import time
password = "pw"
command = "sh ver"
term = "term len 0"
data = open("hostlist.txt")
for line in data:
cmd1 = "enable"
tn = telnetlib.Telnet(line.rstrip())
tn.set_debuglevel(1)
time.sleep(2)
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
time.sleep(2)
tn.write(cmd1.encode('ascii') + b"\n")
time.sleep(2)
tn.write(password.encode('ascii') + b"\n")
time.sleep(2)
tn.write(term.encode('ascii') + b"\n")
tn.write(command.encode('ascii') + b"\n")
time.sleep(2)
tn.write(b"\n")
time.sleep(2)
tn.write(b"\n")
time.sleep(2)
tn.write(b"exit\n")
lastpost = tn.read_all().decode('ascii')
print(lastpost)
op=open ("output.txt", "a").write(lastpost)
tn.close()