我正在做一个项目,该项目是从多个交换机收集某些信息。请记住,我是 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()
我还试图弄清楚是否有某种方法可以只打印开关的最后一个输出,而不是 lastpost = tn.read_all().decode('ascii')
发布整个 telnet session ?
最佳答案
工作代码:
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()
关于Python 3,telnet 自动化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28987822/