Of course! Writing data to a Telnet connection in Python is a common task for automating network devices, testing services, or interacting with legacy systems.

The best and most modern way to do this is by using Python's built-in telnetlib module. It's simple, requires no external installations, and is perfect for most use cases.
Here’s a complete guide, from a basic example to more advanced scenarios.
The Basic telnetlib Example
This example connects to a Telnet server, logs in, sends a command, and reads the response.
Key Steps:
- Import the
telnetlibmodule. - Connect to the host and port using
telnetlib.Telnet(). - Read the initial login prompt.
- Write the username and wait for the password prompt.
- Write the password.
- Send your command using
write(). Remember to append a newline (\n) to most commands. - Read the output from the command.
- Close the connection.
import telnetlib
import time
# --- Configuration ---
HOST = "192.168.1.1" # IP address or hostname of the Telnet server
PORT = 23 # Default Telnet port
USERNAME = "admin"
PASSWORD = "password"
COMMAND = "show version" # Example command for a network device
# --- Main Logic ---
try:
# 1. Connect to the Telnet server
print(f"Connecting to {HOST}:{PORT}...")
tn = telnetlib.Telnet(HOST, PORT, timeout=10) # 10 second timeout
# 2. Read the initial buffer until a login prompt is found
# We use read_until() to wait for specific text.
tn.read_until(b"login: ", timeout=5)
# 3. Write the username and a newline character
tn.write(USERNAME.encode('ascii') + b"\n")
# 4. Read the password prompt
tn.read_until(b"Password: ", timeout=5)
# 5. Write the password and a newline character
tn.write(PASSWORD.encode('ascii') + b"\n")
# 6. Wait for the command prompt to appear, indicating a successful login
# The prompt can vary (e.g., '>', '#', '$'), so adjust as needed.
tn.read_until(b"# ", timeout=5)
print("Login successful.")
# 7. Send the command
print(f"Sending command: '{COMMAND}'")
tn.write(COMMAND.encode('ascii') + b"\n")
# 8. Read the output of the command
# We add a small sleep to ensure the command has finished executing.
time.sleep(1)
output = tn.read_very_eager() # Reads all available data without waiting
# 9. Print the output (decoded from bytes to string)
print("\n--- Command Output ---")
print(output.decode('ascii'))
print("----------------------\n")
except ConnectionRefusedError:
print(f"Error: Connection to {HOST}:{PORT} was refused. Is the server running?")
except TimeoutError:
print(f"Error: Connection to {HOST}:{PORT} timed out.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
# 10. Close the connection
if 'tn' in locals() and tn.get_socket() is not None:
tn.close()
print("Connection closed.")
Detailed Breakdown of telnetlib Methods
| Method | Description | Example |
|---|---|---|
telnetlib.Telnet(host, port, timeout) |
Creates a new Telnet object and connects to the specified host and port. | tn = telnetlib.Telnet('example.com', 2323) |
write(data) |
Writes data to the socket. The data must be in bytes. | tn.write(b"show interfaces\n") |
read_until(expected, timeout) |
Reads data from the socket until it finds the expected bytes. It will raise an error if it times out. |
tn.read_until(b"login: ", 5) |
read_all() |
Reads all data from the socket until the connection is closed. | output = tn.read_all() |
read_very_eager() |
Reads all data that is immediately available without blocking. | output = tn.read_very_eager() |
close() |
Closes the Telnet connection. | tn.close() |
Handling Prompts and Expecting Specific Output
Real-world devices often have complex prompts. A simple read_until might not be enough. For this, the telnetlib expect() method is extremely powerful.

expect() takes a list of regular byte patterns to look for and returns a tuple containing:
- The index of the matched pattern.
- The matched bytes (the match object).
- The bytes read up to the match.
Example using expect():
This is more robust as it handles different possible prompts.
import telnetlib
import re
HOST = "192.168.1.1"
USERNAME = "admin"
PASSWORD = "password"
tn = telnetlib.Telnet(HOST)
# Define the patterns we are looking for (as byte strings)
# Note: b'>' and b'#' are common command prompts
patterns = [
b"login: ",
b"Password: ",
b">",
b"#"
]
try:
# Wait for either a login prompt or a command prompt
# index 0 is for "login: ", index 2 is for ">"
match_index, match_obj, _ = tn.expect(patterns, timeout=10)
if match_index == 0: # Got "login: "
print("Sending username...")
tn.write(USERNAME.encode('ascii') + b"\n")
# Now expect the password prompt or a command prompt
match_index, match_obj, _ = tn.expect([b"Password: ", b"#"], timeout=5)
if match_index == 0: # Got "Password: "
print("Sending password...")
tn.write(PASSWORD.encode('ascii') + b"\n")
# else, it might have logged in directly with the username
# Wait for the final command prompt after login
tn.expect([b"#", b">"], timeout=5)
print("Login successful.")
tn.write(b"show run | include hostname\n")
time.sleep(2)
output = tn.read_very_eager()
print(output.decode('ascii'))
finally:
tn.close()
Important Considerations
A. Newline Characters (\n)
Most network equipment expects commands to be terminated with a newline character (\n). The Telnet protocol specifies \r\n (Carriage Return + Newline), but many devices are forgiving and will accept just \n. It's safest to use \r\n.
# Best practice for commands tn.write(b"show interfaces\r\n")
B. Encoding
telnetlib works with bytes, not strings. You must encode your strings (like usernames, passwords, and commands) before sending them. ascii or utf-8 are common choices.

# Correct
tn.write("my_username".encode('ascii') + b"\n")
# Incorrect (will raise an error)
# tn.write("my_username\n")
C. Timing and Delays
Some devices, especially slower or older ones, can take time to process a command and send back a prompt. If you read too quickly, you might miss the output.
time.sleep(): A simple way to pause execution.read_until(): The preferred method, as it waits for a specific signal (like a prompt) before proceeding.read_very_eager(): Use this when you're sure the server has finished sending and you just want to grab whatever is in the buffer.
D. Security Warning
Telnet sends all data, including usernames and passwords, in plain text. It is completely insecure and should never be used over a public network or for any sensitive application. For modern applications, always use SSH (Secure Shell).
For SSH in Python, the recommended library is paramiko.
# Example using Paramiko for SSH (the secure alternative)
import paramiko
HOST = "192.168.1.1"
USERNAME = "admin"
PASSWORD = "password"
COMMAND = "show version"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Note: This is insecure for production
try:
ssh.connect(HOST, username=USERNAME, password=PASSWORD)
stdin, stdout, stderr = ssh.exec_command(COMMAND)
print("--- Command Output ---")
print(stdout.read().decode())
print("----------------------\n")
print("--- Error Output ---")
print(stderr.read().decode())
print("--------------------\n")
finally:
ssh.close()
print("SSH connection closed.") 