使用telnetlib模块进行telnet连接的工具类
import telnetlib
from time import sleep
class Telnet_Class:
"""Telnet_Class"""
hostIP = 'root'
TCP_Port = 23
timeOut = 60
def __init__(self, hostIP='', TCP_Port=23, timeOut=60):
self.hostIP = hostIP
self.TCP_Port = TCP_Port
self.timeOut = timeOut
def getConnectObject(self):
"""获取,并打开Telnet连接"""
try:
return telnetlib.Telnet(self.hostIP,self.TCP_Port,self.timeOut)
except Exception:
raise Exception("Get Telnet Connect Object Failed!")
def closeTelnetObject(self, telnetObject):
"""关闭Telnet连接"""
try:
telnetObject.close()
return True
except Exception :
raise Exception("Close Telnet Connect Object Failed!")
finally:
return None
def executeTelnetCommands(self, telnetObject, My_Commands):
"""必须是已经登录成功的才可以执行命令"""
if My_Commands:
for command in My_Commands:
telnetObject.write(command.encode())
print(telnetObject.read_until(b'#').decode())
sleep(1)
return True
else:
return None
def telnetLogin(self, telnetObject, userName, passWord):
"""执行登录,不同服务存在不同差异,使用时请注意修改"""
sleep(1)
telnetObject.write(userName.encode())
print(telnetObject.read_until(b':').decode())
sleep(1)
telnetObject.write(passWord.encode())
print(telnetObject.read_until(b'#').decode())
sleep(1)
if __name__ == '__main__':
"""连接示例"""
My_Commands=['\r\n','\r\n','ls\r\n','\r\n','\r\n']
TelnetClass = Telnet_Class(hostIP='192.168.0.2')
telnetobject = TelnetClass.getConnectObject()
TelnetClass.telnetLogin(telnetobject,'root\r\n','root\r\n')
TelnetClass.executeTelnetCommands(telnetobject,My_Commands)
TelnetClass.closeTelnetObject(telnetobject)
|