Network engineers learn Python-38-telnetlib improved version Telnetlib3

Telnetlib3 is a telnet client library for Python that can be used to access the server remotely. It is an improved version of the Python standard library telnetlib, supports Python 3.x version, and provides some new features. In this article, we will explore how to use the Telnetlib3 framework for remote access and provide some sample code.

Install

Before using Telnetlib3, you need to install it. It can be installed using the pip command as follows:

pip install telnetlib3

Connect to remote server

The steps to connect to the remote server are as follows:

import telnetlib3

async def main():
    tn = await telnetlib3.open_connection('hostname', 23)
    await tn.login('username', 'password')

asyncio.run(main())

In the above code, we use the open_connection() method to connect to the remote server. It takes two parameters, hostname and port number. After the connection is successful, we use the login() method to authenticate. It requires two parameters, username and password. In this way, we can successfully connect to the remote server.

send command

We can use the Telnetlib3 framework to send commands to the remote server and get the output from the server. Below is an example:

import telnetlib3

async def main():
    tn = await telnetlib3.open_connection('hostname', 23)
    await tn.login('username', 'password')

    await tn.shell('ls -l')
    response = await tn.read_until(b'$')
    print(response.decode())

asyncio.run(main())

In the above code, we use shell() method to send the command. In this example, we sent an ls -l command. We then use the read_until() method to read the server's output. This method receives one parameter, which is the end flag of the read data. In this example, we use $ as the ending flag. Finally, we print the server's output to the console.

Disconnect

After using Telnetlib3, you need to disconnect from the remote server. The connection can be closed using the close() method, as shown below:

import telnetlib3

async def main():
    tn = await telnetlib3.open_connection('hostname', 23)
    await tn.login('username', 'password')

    await tn.close()

asyncio.run(main())

Summarize

In this article, we introduced how to use the Telnetlib3 framework for remote access. We learned how to connect to a remote server, send commands, and disconnect. The sample code given here is just the tip of the iceberg of the Telnetlib3 framework. Telnetlib3 also provides many other features. By learning Telnetlib3 in depth, you can better utilize its features for better remote access.

Guess you like

Origin blog.csdn.net/weixin_43025343/article/details/132638778