The right way to create telnet consumer with asyncio in Python



Telnet is a consumer/server software protocol that makes use of TCP/IP for connection. Telnet protocol permits a person to log onto and use a distant pc as if they have been linked on to it throughout the native community. The system that’s being utilized by the person for the connection is the consumer and the distant pc being linked is the server. The instructions entered on the terminal in a Telnet consumer are executed on the server (the distant pc) and the output of the command is directed to the consumer pc’s display screen. Telnet is insecure because it makes use of plain textual content communication. The safe implementation of telnet that makes use of cryptography to encrypt information being transferred is SSH (Safe Shell). The telnet protocol is I/O certain, the I/O may be very sluggish for e.g, the institution of a reference to the server might take a very long time on account of sluggish pace on the server facet, this ends in a whole lot of idle CPU time since many such connections have to be created to the server, the asyncio library is essentially the most appropriate for such a process. 

Asyncio (Asynchronous Enter/Output) is a python library for concurrent programming. Asynchronous is a mode of programming by which two processes are being executed on the identical time (not concurrently). There is just one CPU core concerned in computation (single thread), on account of which the duties take turns for execution and processing. Process 1 might begin first after which mid-process the CPU begins execution of Process 2, the CPU might select to change between the duties to optimize the utilization of sources and reduce idle time.  

Steps to create a telnet consumer

1. Outline an asynchronous telnet consumer perform 

Utilizing the asyncio.open_connection() coroutine with parameters host, port open a connection to the server, this perform returns a reader and a author which can be cases of the category Streamerader and Streamwriter. These objects are used to learn from the server and write to the server.

Write the username and password by means of the Streamwriter object to authenticate.

The assertion awaits the reader.readline() returns a line that’s obtained from the server, and yields the management whereas ready for a response from the server, yielding management means informing the occasion loop that whereas the coroutine is ready for a response go on and use the processing energy for different computations. Print the response that’s obtained from the server.

As soon as a connection is established efficiently the author object of the Streamwriter class can be utilized to ship textual content instructions that the server can implement domestically and the outcomes will be learn through the thing of the Streamreader class.

Shut the connection.

2. Outline an asynchronous principal 

Inside the primary perform name the telnet_client() coroutine with parameters hostname, a port that the server is listening on, username, and password. The await name yields the management whereas the telnet_client() coroutine is ready for a connection. 

3. Asynchronous run the primary perform

The highest-level entry level principal() coroutine (since it’s outlined with async def) doesn’t implement itself however quite must be run with the command. 


import asyncio



async def telnet_client(host: str, port: int, username: str, password: str) -> None:

    reader, author = await asyncio.open_connection(host, port)

    print(f"linked to ({host}, {port})")






    whereas True:

        command = enter("nEnter a command: ")

        if not command:

            print("[No command] ...closing connection ")



        information = await reader.learn(100000)

        print(information.decode().strip())"", 2000, "username", "password"))

Telnet server

To check the consumer you need to have a server to determine a connection to, following is a neighborhood server in python listening on port 2000. The setup is similar to the consumer with the handle_client perform working because the asynchronous listener. The run_command perform spawns a course of with command com, the stdin, stdout, stderr streams of the shell are captured and the info is returned to the consumer utilizing the StreamWriter.


import asyncio

import subprocess



def run_command(com: str) -> None:


        professional = up(), capture_output=True, textual content=True)

        if professional.stdout:

            return f"out----------------n{professional.stdout}"

        elif professional.stderr:

            return f"err----------------n {professional.stderr}"


            return f"[executed]"

    besides Exception as ex:

        print("exception occured", ex)

        return f"   [subprocess broke]"



async def handle_client(reader, author):

    print(f"Linked to {author.get_extra_info('peername')}")


    whereas True:

        information = await reader.learn(100000)

        message = information.decode().strip()

        if not message:


        print(f"Obtained message: {message}")

        res = run_command(message)


    print("Closing connection")




async def start_server():

    server = await asyncio.start_server(handle_client, "", 2000)

    print("Server began")

    await server.serve_forever()

Now run the next command within the terminal:



server began

consumer linked

instructions executed