Python-Telnet连接工具类
生活随笔
收集整理的這篇文章主要介紹了
Python-Telnet连接工具类
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
使用telnetlib模塊進(jìn)行telnet連接的工具類
import telnetlib from time import sleepclass Telnet_Class:"""Telnet_Class"""hostIP = 'root'TCP_Port = 23timeOut = 60def __init__(self, hostIP='', TCP_Port=23, timeOut=60):self.hostIP = hostIPself.TCP_Port = TCP_Portself.timeOut = timeOutdef 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):"""關(guān)閉Telnet連接"""try:telnetObject.close()return Trueexcept Exception :raise Exception("Close Telnet Connect Object Failed!")finally:return Nonedef executeTelnetCommands(self, telnetObject, My_Commands):"""必須是已經(jīng)登錄成功的才可以執(zhí)行命令"""if My_Commands:for command in My_Commands:telnetObject.write(command.encode())print(telnetObject.read_until(b'#').decode())sleep(1)return Trueelse:return Nonedef telnetLogin(self, telnetObject, userName, passWord):"""執(zhí)行登錄,不同服務(wù)存在不同差異,使用時(shí)請(qǐng)注意修改"""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)總結(jié)
以上是生活随笔為你收集整理的Python-Telnet连接工具类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Weblogic EJB 学习笔记(2)
- 下一篇: 特征选择算法之ReliefF算法pyth