import telnetlib import time class TelnetClient(object): def __init__(self, addr, port=23): self.addr = addr self.port = port self.timeout = 5000 def init(self,): if not self.con: self.open() def open(self): tn = telnetlib.Telnet(host=self.addr, port=self.port, timeout=self.timeout) self.con = tn def send_cmd(self, cmd_list): resver = [] for cmd in cmd_list: self.con.write(cmd + b"\r\n") time.sleep(0.3) resver.append(self.con.read_very_eager()) return b"\n".join(resver).decode() def close(self): self.send_cmd("exit") if self.con is not None: self.con.close() self.con = None