DEV Community

Cover image for Telnet multiple hosts with telnetlib3
Raymond
Raymond

Posted on

Telnet multiple hosts with telnetlib3

Why did I create this script?

When you set up the new environment, you need to check whether all hosts and ports are reachable or not but you don’t want to execute telnet host port multiple times. It is a boring step that sometimes you may make a mistake here so I need to create a script to telnet multiple hosts with telnetlib3 library.

(telnetlib will be deprecated in the new version)

Requirements

Python > 3.7

Setup

Step 1: Install telnetlib3

pip install telnetlib3
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a main.py file

import asyncio
import telnetlib3
import io

async def telnet_welcome_message(telnet_host, telnet_port):
    telnet_connection = True
    try:
        await asyncio.wait_for(telnetlib3.open_connection(telnet_host, telnet_port), 5)
    except (asyncio.exceptions.TimeoutError, OSError) as e:
        telnet_connection = False
        print(e)
    return telnet_connection

failed_connection = []

with open("server.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        info = line.split(",")
        host = info[0]
        port = int(info[1])
        connection = asyncio.run(telnet_welcome_message(host, port))
        if not connection:
            failed_connection.append({"host": host, "port": port})

print(failed_connection)
Enter fullscreen mode Exit fullscreen mode

This script states that the hosts and ports are reachable for 5 minutes, if a timeout or denied, it returns the failed connections.

Step 3: Create a server.txt file that contains the host and port like this

192.168.1.1,8080
192.168.10.1,8191
Enter fullscreen mode Exit fullscreen mode

Step 4: Execute the below command to see which IP and port are not reached

python main.py
Enter fullscreen mode Exit fullscreen mode

Preferences

https://telnetlib3.readthedocs.io/en/latest/intro.html

Top comments (0)