python telnetlib 模块的使用

时间:2021-09-05 03:03:55

利用telnetlib模块实现telnet登陆到Huawei OLT,执行相关命令,并把结果保存到config.txt文档。

import telnetlib
import getpass
import sys

HOST = "x.x.x.x"
user = "test"
password = "123456"
spacetime = 1

tn = telnetlib.Telnet(HOST)
tn.read_until("User name:")
tn.write(user+"\n")
tn.read_until("User password:")
tn.write(password+"\n")
tn.read_until(">")
tn.write("enable\n")
tn.read_until("#")
#tn.write("display ont info 0 1 0 14\n")
tn.write("display ont autofind all\n")
tn.read_until(":")
tn.write("\n")
while spacetime <= 5:
    tn.write(" ")
    spacetime = spacetime + 1
msg=tn.read_until("#")
tn.write("quit\n")
tn.read_until("(y/n)[n]:")
tn.write("y\n")


path = r"f:\config.txt"
f = file(path,"wb")
f.write(msg)
f.close()

tn.close