我编写了一个脚本来执行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
我想在另一个程序中使用此脚本,该程序将通过telneting来检查路由器的版本。我期待一个脚本,它将调用我的上述函数执行telnet并发送其他命令即。 "版本"或" ls"
答案 0 :(得分:1)
尝试使其更像一个类:
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()