我想了解如何在简单的场景中使用 telnetlib3。
长期存在的 telnetlib(不是 3)在https://docs.python.org/3/library/telnetlib.html有一个简单的示例,其中 python 程序连接到 telnet 服务器,然后查找提示并提供响应。人们可以很容易地看到如何将此示例扩展到不同的提示、添加超时以及添加更多提示响应步骤。
import getpass
import telnetlib
HOST = "localhost"
user = input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until(b"login: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
tn.write(b"ls\n")
tn.write(b"exit\n")
print(tn.read_all().decode('ascii'))
Run Code Online (Sandbox Code Playgroud)
但是,telnetlib(不是 3)已被弃用。
替代品 telnetlib3 ( https://telnetlib3.readthedocs.io/en/latest/intro.html#quick-example ) 提供了一个基于 asyncio 的示例,并且异步“shell”函数(与服务器交互)阻塞等待提示(异步的基本原理)并始终用“y”响应服务器。
import asyncio, telnetlib3
async def shell(reader, writer):
while True:
# read stream until '?' mark is found
outp = await reader.read(1024)
if not outp: …Run Code Online (Sandbox Code Playgroud)