Your First Network Script: Telnet with Python

Learn network automation basics by creating your first Python script using telnetlib to connect to routers in GNS3 or Packet Tracer. Perfect introduction to automation concepts before moving to more secure protocols.

Your First Network Script: Telnet with Python

Ready to take your first steps into network automation? Let's start with a practical example that connects Python to network devices using the built-in telnetlib module. While Telnet isn't secure for production networks, it's a useful starting point for learning automation concepts in your lab environment — and the patterns you'll learn here transfer directly to SSH-based tools like Netmiko and Paramiko.

Why Start with Telnet?

Before diving into SSH and more advanced protocols, python telnet provides a useful introduction to network automation because:

  • No additional libraries required: telnetlib comes built into Python (see the version note below)
  • Simple communication makes it easier to see exactly what's happening during the connection process
  • Works in GNS3 and other lab environments where Telnet is deliberately enabled for practice
  • Teaches the fundamental read/write automation pattern without additional abstraction

Important — Python version compatibility: telnetlib was deprecated in Python 3.11 and removed entirely in Python 3.13. If you're running Python 3.13 or later, this module won't be available. Check your version with python --version. If you're on 3.13+, use Python 3.11 or 3.12 for this exercise, or skip ahead to the Netmiko/SSH post in this series.

Important — Security: Telnet sends credentials and data in plain text. Never use this in production networks. It's strictly for isolated lab environments where you have full control of the network.

Setting Up Your Lab

For this example, configure a basic router in GNS3 with Telnet enabled. GNS3 is a free network simulator that runs actual Cisco IOS images. Download it from gns3.com and follow their quickstart guide to get a router running. Once your router is up, apply this configuration:

Router(config)# line vty 0 4
Router(config-line)# password cisco
Router(config-line)# login
Router(config-line)# transport input telnet
Router(config-line)# exit
Router(config)# enable password cisco

Ensure your router has an IP address (like 192.168.1.1) that your Python script can reach. You can verify this with a simple ping 192.168.1.1 from your machine before running the script.

Your First Network Script

Here's a complete network automation beginner script that connects to a router and retrieves basic information:

import telnetlib
import time
import socket
Connection details
HOST = "192.168.1.1"
PORT = 23
TIMEOUT = 10  # Seconds to wait before giving up on connection
USERNAME = ""  # Leave empty if no username required
PASSWORD = "cisco"
ENABLE_PASSWORD = "cisco"
def connect_to_router():
"""Establish a Telnet connection with timeout handling."""
try:
tn = telnetlib.Telnet(HOST, PORT, TIMEOUT)
except socket.timeout:
raise ConnectionError(f"Timed out connecting to {HOST}. Is the device reachable?")
except ConnectionRefusedError:
raise ConnectionError(f"Connection refused by {HOST}. Is Telnet enabled on the device?")
# Handle login (if username is configured)
if USERNAME:
    tn.read_until(b"Username: ", timeout=TIMEOUT)
    tn.write(USERNAME.encode('ascii') + b"\n")

# Send password
tn.read_until(b"Password: ", timeout=TIMEOUT)
tn.write(PASSWORD.encode('ascii') + b"\n")

# Enter enable mode
tn.write(b"enable\n")
tn.read_until(b"Password: ", timeout=TIMEOUT)
tn.write(ENABLE_PASSWORD.encode('ascii') + b"\n")

# Wait for privileged prompt and disable paging
tn.read_until(b"#", timeout=TIMEOUT)
tn.write(b"terminal length 0\n")
tn.read_until(b"#", timeout=TIMEOUT)

return tn

def send_command(tn, command):
"""Send a command and return the output."""
tn.write(command.encode('ascii') + b"\n")
time.sleep(1)  # Give command time to execute
output = tn.read_very_eager().decode('ascii')
return output
def main():
connection = None
try:
print("Connecting to router...")
connection = connect_to_router()
print("Connected successfully!")
    commands = ["show version", "show ip interface brief", "show running-config"]

    for cmd in commands:
        print(f"\n--- Executing: {cmd} ---")
        result = send_command(connection, cmd)
        print(result)

except ConnectionError as e:
    print(f"Connection failed: {e}")
except EOFError:
    print("Connection dropped unexpectedly. The device may have closed the session.")
except Exception as e:
    print(f"Unexpected error: {e}")
finally:
    if connection:
        connection.close()
        print("\nConnection closed.")

Understanding the Script

Let's break down the key components:

Connection Setup

The telnetlib.Telnet(HOST, PORT, TIMEOUT) call now includes a timeout value. Without this, if the device is unreachable the script will hang indefinitely — which is a common problem when running automation against real or simulated devices. The socket.timeout and ConnectionRefusedError exceptions handle the two most common connection failures separately, giving you a clear error message instead of a generic traceback.

Command Execution

The send_command() function demonstrates the basic pattern for network automation: send a command, wait for execution, then read the output. The time.sleep(1) ensures the command completes before reading results. Each read_until() call also now includes a timeout, so the script won't hang waiting for a prompt that never arrives.

Error Handling

The finally block ensures the connection is always closed cleanly, even if an error occurs mid-script. This prevents the device from leaving stale VTY sessions open. Network automation scripts should always clean up connections — leaving sessions open can exhaust the device's VTY line limit and lock out other users.

Running Your Script

Save the script as telnet_router.py and run it:

python telnet_router.py

You should see output showing the connection process and command results from your router.

Common Troubleshooting Tips

  • ModuleNotFoundError for telnetlib: You're running Python 3.13 or later — telnetlib was removed. Use Python 3.11 or 3.12 for this exercise
  • Connection timeout: Verify the router IP is reachable with a ping before running the script
  • Connection refused: Check that Telnet is enabled on the VTY lines with transport input telnet
  • Login failures: Verify passwords and VTY line configuration
  • Incomplete output: Increase the time.sleep() value for slower devices
  • Encoding errors: Ensure you're using .encode('ascii') for commands

What's Next

Now that you understand the fundamentals of connecting Python to network devices, prompts, read/write cycles, and connection handling, our next post moves to SSH with the Netmiko library. Netmiko abstracts away the low-level prompt handling you've done manually here, supports dozens of device types, and is the standard tool for production network automation. The concepts you've learned in this post map directly across.