telnetlib3 快速上手

telnetlib3 快速上手#

telnetlib3 是 Python 3 asyncio Telnet 服务器和客户端协议库。

telnetlib3 示例#

使用提供基本战争游戏的流接口编写 Telnet 服务器:

import asyncio, telnetlib3

async def shell(reader, writer):
    writer.write('\r\nWould you like to play a game? ')
    inp = await reader.read(1)
    if inp:
        writer.echo(inp)
        writer.write('\r\nThey say the only way to win '
                     'is to not play at all.\r\n')
        await writer.drain()
    writer.close()

coro = telnetlib3.create_server(port=6023, shell=shell)
loop = asyncio.get_event_loop()
server = loop.run_until_complete(coro)
loop.run_until_complete(server.wait_closed())

编写一个与该服务器玩战争游戏的 Telnet 客户端:

import asyncio, telnetlib3

async def shell(reader, writer):
    while True:
        # read stream until '?' mark is found
        outp = await reader.read(1024)
        if not outp:
            # End of File
            break
        elif '?' in outp:
            # reply all questions with 'y'.
            writer.write('y')

        # display all server output
        print(outp, flush=True)

    # EOF
    print()

coro = telnetlib3.open_connection('localhost', 6023, shell=shell)

loop = asyncio.get_event_loop()
reader, writer = loop.run_until_complete(coro)
loop.run_until_complete(writer.protocol.waiter_closed)

命令行脚本#

这个包附带了两个命令行脚本。

  • telnetlib3-client 小型终端 telnet 客户端。以下是一些示例目标和选项:

    telnetlib3-client nethack.alt.org
    telnetlib3-client --encoding=cp437 --force-binary blackflag.acid.org
    telnetlib3-client htc.zapto.org
    
  • telnetlib3-server 提供默认调试 shell 的 telnet 服务器提供简单的 shell 服务器,允许对会话的值进行自省,例如:

    tel:sh> help
    quit, writer, slc, toggle [option|all], reader, proto
    
    tel:sh> writer
    <TelnetWriter server mode:kludge +lineflow -xon_any +slc_sim server-will:BINARY,ECHO,SGA client-will:BINARY,NAWS,NEW_ENVIRON,TTYPE>
    
    tel:sh> reader
    <TelnetReaderUnicode encoding='utf8' limit=65536 buflen=0 eof=False>
    
    tel:sh> toggle all
    wont echo.
    wont suppress go-ahead.
    wont outbinary.
    dont inbinary.
    xon-any enabled.
    lineflow disabled.
    
    tel:sh> reader
    <TelnetReaderUnicode encoding='US-ASCII' limit=65536 buflen=1 eof=False>
    
    tel:sh> writer
    <TelnetWriter server mode:local -lineflow +xon_any +slc_sim client-will:NAWS,NEW_ENVIRON,TTYPE>
    

这两个命令行脚本都接受参数 --shell=my_module.fn_shell,描述 Python 模块路径到签名为 shell(reader, writer) 的协程,就像上面的示例一样。