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
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)
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
Step 4: Execute the below command to see which IP and port are not reached
python main.py
Top comments (0)