Skip to content

Commit 43a3233

Browse files
authored
Refactor telnet_tutor.py to use asyncio and telnetlib3
1 parent fc2b4ce commit 43a3233

1 file changed

Lines changed: 37 additions & 25 deletions

File tree

ForNicole/tools/telnet_tutor.py

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,42 @@
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
53

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
810

9-
HOST = "telehack.com" # a public sandboxed telnet playground
11+
HOST, PORT = "telehack.com", 23
1012

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():
2714
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.")
2937
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

Comments
 (0)