https://blog.youkuaiyun.com/qq_59142194/article/details/123937365
from telnetlib import Telnet
from threading import Thread
from tkinter import IntVar, StringVar
import ttkbootstrap as ttk
from ttkbootstrap.dialogs import Messagebox
from time import sleep
host = "127.0.0.1"
port = 23
timeout = 30
tn = None
tn_ready = False
text = None
running = True
def myasync(f):
def wrapper(*args, **kwargs):
thr = Thread(target=f, args=args, kwargs=kwargs)
thr.daemon = True
thr.start()
return wrapper
def telnet_connect():
global tn, tn_ready, _ip, _port
if not tn:
try:
tn = Telnet(host=_ip.get(), port=_port.get(), timeout=timeout)
except Exception as e:
Messagebox.ok(message=str(e))
return
tn.read_until(b"login: ")
tn.write(b"u\n")
tn.read_until(b"Password: ")
tn.write(b"0\n")
tn_ready = True
telnet_show()
@myasync
def telnet_show():
global tn, tn_ready, text, running
while running:
if tn and tn_ready and running:
while tn and tn_ready and running:
textc = tn.read_some().decode("utf8")
if text:
text.insert(ttk.END, textc)
text.see(ttk.END)
print(textc, end='')
else:
sleep(0.01)
def telnet_send(text, s):
global tn
if tn or True:
tn.write(s.encode("utf8") + b"\n")
text.see(ttk.END)
def btn_command(text: ttk.Text):
text.insert(ttk.END, "ttttttttttttttt")
text.see(ttk.END)
if __name__ == "__main__":
root = ttk.Window(
title="Mini Teminal",
themename="litera",
size=(1920, 1080),
minsize=(1920, 1080),
maxsize=(1920, 1080),
resizable=None,
alpha=1.0,
)
text = ttk.Text(root)
text.configure(width=120)
text.grid(row=0, column=0, rowspan=10, columnspan=10, sticky=ttk.NSEW)
text.insert(ttk.END, "ttttttttttttttt")
text.see(ttk.END)
_ip = StringVar(root)
_ip.set("127.0.0.1")
_port = IntVar(root)
_port.set(23)
ttk.Entry(root, show=None, textvariable=_ip).grid(row=1, column=11)
ttk.Entry(root, show=None, textvariable=_port).grid(row=1, column=12)
ttk.Button(
root,
text="连接",
command=lambda: telnet_connect(),
bootstyle=(ttk.PRIMARY, "outline-toolbutton"),
).grid(row=2, column=11)
ttk.Button(
root,
text="ls",
command=lambda: telnet_send(text, "ls"),
bootstyle=(ttk.PRIMARY, "outline-toolbutton"),
).grid(row=2, column=12)
root.mainloop()
running = False