telnetlib3: Async Telnet Server and Client

4.0.2 · active · verified Sat Apr 11

telnetlib3 is an asynchronous Python library for building Telnet servers and clients, supporting a wide array of Telnet Option specifications (RFCs). It offers both a programmatic API and command-line utilities. Currently at version 4.0.2, it maintains an active release cadence with frequent bug fixes and feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic Telnet server using `telnetlib3`. It sets up an asynchronous server that echoes back any text received from connected clients. The server listens on port 6023 by default, or a port specified by the `TELNET_PORT` environment variable. To test, run this script and then connect with `telnet localhost 6023` in another terminal.

import telnetlib3
import asyncio
import os

async def simple_shell(reader, writer):
    peername = writer.get_extra_info('peername')
    print(f'Client {peername} connected.')
    writer.write(f'Hello, {peername}! Type something and press Enter (or Ctrl+C to quit).
')
    while True:
        try:
            text = await reader.read(1024)
            if not text:
                break
            print(f'Received from {peername}: {text!r}')
            writer.write(f'You said: {text!r}
')
            await writer.drain()
        except asyncio.IncompleteReadError:
            break # Client disconnected
        except ConnectionResetError:
            break # Client forcibly closed

    print(f'Client {peername} disconnected.')

async def main():
    # Use os.environ for port to make it runnable without hardcoding
    port = int(os.environ.get('TELNET_PORT', '6023'))
    server = await telnetlib3.create_server(port=port, shell=simple_shell)
    print(f"Telnet server listening on port {port}")
    async with server:
        await server.serve_forever()

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("Server stopped gracefully.")

view raw JSON →