Python-Telnet连接工具类
生活随笔
收集整理的這篇文章主要介紹了
Python-Telnet连接工具类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用telnetlib模塊進行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):"""關閉Telnet連接"""try:telnetObject.close()return Trueexcept Exception :raise Exception("Close Telnet Connect Object Failed!")finally:return Nonedef 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 Trueelse:return Nonedef 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)總結
以上是生活随笔為你收集整理的Python-Telnet连接工具类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Weblogic EJB 学习笔记(2)
- 下一篇: 特征选择算法之ReliefF算法pyth