我编写了一个执行 telnet 的脚本,我想用它来向我的被测设备(路由器)发送命令。
我的 Telnet 脚本:
import sys, time, telnetlib
sys.path.insert(0, '/tmp')
import options
def telnet_connect():
HOST = "%s" %options.DUT_telnet_ip
PORT = "%s" %options.DUT_telnet_port
username = "%s" %options.DUT_telnet_username
password = "%s" %options.DUT_telnet_password
tn = telnetlib.Telnet(HOST, PORT, 10)
time.sleep(5)
tn.write("\n")
tn.read_until("login:", 2)
tn.write(username)
tn.read_until("Password:", 2)
tn.write(password)
tn.write("\n")
response = tn.read_until("$", 5)
return response
def telnet_close():
response = tn.write("exit\n")
return response
<小时/>
我想在另一个程序中使用此脚本,该程序将通过远程登录来检查路由器的版本。我期望一个脚本将调用我的上述函数来执行 telnet 并发送其他命令即。 “版本”或“ls”
最佳答案
尝试使其更像一个类:
import sys, time, telnetlib
sys.path.insert(0, '/tmp')
class TelnetConnection():
def init(self, HOST, PORT):
self.tn = telnetlib.Telnet(HOST, PORT, 10)
def connect(self, username, password):
tn = self.tn
tn.write("\n")
tn.read_until("login:", 2)
tn.write(username)
tn.read_until("Password:", 2)
tn.write(password)
tn.write("\n")
response = tn.read_until("$", 5)
return response
def close(self):
tn = self.tn
response = tn.write("exit\n")
return response
# create here then a method to communicate as you wish
然后您可以按如下方式使用它:
import options
HOST = "%s" %options.DUT_telnet_ip
PORT = "%s" %options.DUT_telnet_port
username = "%s" %options.DUT_telnet_username
password = "%s" %options.DUT_telnet_password
connection = TelnetConnection(HOST, PORT)
connection.connect(username, password)
connection.do_all_operations_you_want() # write your own method for that
connection.close()
关于python - 如何与路由器通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39103719/