"""Минимальный telnet-клиент к Keenetic CLI (без telnetlib).""" import re import socket import sys import time HOST = sys.argv[1] if len(sys.argv) > 1 else "192.168.1.185" PORT = 23 USER = "admin" PASSWORD = "73145146" IAC, DONT, DO, WONT, WILL, SB, SE = 255, 254, 253, 252, 251, 250, 240 def negotiate(data, sock): """Отвечает на telnet-переговоры и вычищает IAC из текста.""" out = bytearray() i = 0 while i < len(data): b = data[i] if b == IAC and i + 1 < len(data): cmd = data[i + 1] if cmd in (DO, DONT, WILL, WONT) and i + 2 < len(data): opt = data[i + 2] if cmd == DO: sock.sendall(bytes([IAC, WONT, opt])) elif cmd == WILL: sock.sendall(bytes([IAC, DONT, opt])) i += 3 continue if cmd == SB: j = data.find(bytes([IAC, SE]), i) i = (j + 2) if j > 0 else len(data) continue i += 2 continue out.append(b) i += 1 return bytes(out) class Telnet: def __init__(self, host, port=23): self.s = socket.create_connection((host, port), timeout=15) self.s.settimeout(3) self.buf = b"" def read(self, wait=1.0): end = time.time() + wait chunks = [] while time.time() < end: try: data = self.s.recv(4096) if not data: break chunks.append(negotiate(data, self.s)) except socket.timeout: continue except Exception: break self.buf += b"".join(chunks) return self.buf.decode("utf-8", "replace") def send(self, line): self.s.sendall(line.encode() + b"\r\n") time.sleep(0.6) return self.read(1.2) def close(self): try: self.s.close() except Exception: pass def main(): t = Telnet(HOST, PORT) text = t.read(2.5) print("-- приветствие --") print(text[-300:]) if re.search(r"login|Login|User", text): print("-- логин --") print(t.send(USER)[-200:]) if re.search(r"[Pp]assword", t.buf.decode("utf-8", "replace")[-300:]): print("-- пароль --") print(t.send(PASSWORD)[-300:]) print("-- кто мы --") print(t.send("show version")[-500:]) t.close() if __name__ == "__main__": main()