Standard Telnetlib Redistribution

3.13.0 · active · verified Thu Apr 16

standard-telnetlib is a redistribution of the `telnetlib` module, which was part of the Python standard library until its removal in Python 3.13 (deprecated in 3.11). It serves as a 'dead battery' backport, providing the original `telnetlib` functionality for projects that require it in Python versions where it's no longer built-in. This library allows developers to continue using the `telnetlib` client functionality without needing to pin older Python versions. The latest version is 3.13.0, released to coincide with Python 3.13's removal of the module.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a Telnet connection, send login credentials, execute a command, read its output, and close the connection. Note that all data sent to and received from the Telnet server must be handled as bytes.

import telnetlib
import getpass
import os

HOST = os.environ.get('TELNET_HOST', 'localhost')
PORT = int(os.environ.get('TELNET_PORT', 23))
USER = os.environ.get('TELNET_USER', 'testuser')

try:
    # Establish connection
    tn = telnetlib.Telnet(HOST, PORT, timeout=5)
    
    # Read until a login prompt, send username
    tn.read_until(b'login: ', timeout=2)
    tn.write(USER.encode('ascii') + b'\n')
    
    # Read until password prompt, send password
    if os.environ.get('TELNET_PASSWORD'): # Only prompt if env var is set
        PASSWORD = getpass.getpass()
        tn.read_until(b'Password: ', timeout=2)
        tn.write(PASSWORD.encode('ascii') + b'\n')
    
    # Example: Send a command and read output
    tn.write(b'ls -l\n')
    output = tn.read_until(b'$ ', timeout=5) # Assuming a common shell prompt
    print(output.decode('ascii'))
    
    tn.write(b'exit\n')
    print(tn.read_all().decode('ascii'))
    
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    if 'tn' in locals() and tn:
        tn.close()

view raw JSON →