|
1 | | -""" |
2 | | -telnet_tutor.py — gentle Telnet demonstration. |
3 | | -Educational use only — no live system access. |
4 | | -""" |
| 1 | +# /Users/dontadaya/PrettyPython/projects/MakeItCute/ForNicole/tools/telnet_tutor.py |
| 2 | +import sys, subprocess, asyncio |
5 | 3 |
|
6 | | -import telnetlib |
7 | | -import time |
| 4 | +# Ensure telnetlib3 is available (Python 3.13+ replacement for stdlib telnetlib) |
| 5 | +try: |
| 6 | + import telnetlib3 # type: ignore |
| 7 | +except Exception: |
| 8 | + subprocess.check_call([sys.executable, "-m", "pip", "install", "--user", "telnetlib3"]) |
| 9 | + import telnetlib3 # type: ignore |
8 | 10 |
|
9 | | -HOST = "telehack.com" # a public sandboxed telnet playground |
| 11 | +HOST, PORT = "telehack.com", 23 |
10 | 12 |
|
11 | | -def connect_demo(): |
12 | | - print("🌐 Connecting to Telehack (a safe retro sandbox)...") |
13 | | - tn = telnetlib.Telnet(HOST) |
14 | | - time.sleep(1) |
15 | | - banner = tn.read_until(b":", timeout=5).decode(errors="ignore") |
16 | | - print("Server says:\n", banner.strip()) |
17 | | - tn.write(b"help\n") |
18 | | - time.sleep(1) |
19 | | - data = tn.read_very_eager().decode(errors="ignore") |
20 | | - print("----- Help excerpt -----") |
21 | | - print("\n".join(data.splitlines()[:20])) |
22 | | - tn.write(b"quit\n") |
23 | | - tn.close() |
24 | | - print("Disconnected gracefully.") |
25 | | - |
26 | | -if __name__ == "__main__": |
| 13 | +async def main(): |
27 | 14 | try: |
28 | | - connect_demo() |
| 15 | + reader, writer = await telnetlib3.open_connection(HOST, PORT, encoding="utf8") |
| 16 | + # ask for help right away |
| 17 | + writer.write("help\n") |
| 18 | + await writer.drain() |
| 19 | + |
| 20 | + try: |
| 21 | + out = await asyncio.wait_for(reader.read(2000), timeout=1.5) |
| 22 | + except asyncio.TimeoutError: |
| 23 | + out = "" |
| 24 | + |
| 25 | + if out: |
| 26 | + print("----- Help excerpt -----") |
| 27 | + print(out[:1000]) |
| 28 | + |
| 29 | + writer.write("quit\n") |
| 30 | + await writer.drain() |
| 31 | + writer.close() |
| 32 | + try: |
| 33 | + await writer.wait_closed() |
| 34 | + except Exception: |
| 35 | + pass |
| 36 | + print("Disconnected.") |
29 | 37 | except Exception as e: |
30 | | - print("❌ Connection error:", e) |
| 38 | + print("Error:", e) |
| 39 | + print("Tip: Some networks block outbound telnet (port 23). Try another network or VPN.") |
| 40 | + |
| 41 | +if __name__ == "__main__": |
| 42 | + asyncio.run(main()) |
0 commit comments