Python Network Programming 简明教程

Python - Telnet

Telnet 是一种网络协议,它允许一台计算机中的用户登录到同一网络中的另一台计算机。Telnet 命令与主机名一起使用,然后输入用户凭据。成功登录后,远程用户可以访问应用程序和数据,方式类似于该系统的普通用户。当然,某些权限可以由系统管理员控制,该管理员设置和维护系统。

Telnet is a type of network protocol which allows a user in one computer to logon to another computer which also belongs to the same network. The telnet command is used along with the host name and then the user credentials are entered. Upon successful login the remote user can access the applications and data in a way similar to the regular user of the system. Of course some privileges can be controlled by the administrator of the system who sets up and maintains the system.

在 Python 中,Telnet 由 telnetlib 模块实现,该模块具有包含所需方法以建立连接的 Telnet 类。在下面的示例中,我们还使用 getpass 模块来处理作为登录过程一部分的密码提示。此外,我们假设连接是与 Unix 主机建立的。下面解释了程序中使用的 telnetlib.Telnet 类的各种方法。

In Python telnet is implemented by the module telnetlib which has the Telnet class which has the required methods to establish the connection. In the below example we also use the getpass module to handle the password prompt as part of the login process. Also we assume the connection is made to a unix host. The various methods from telnetlib.Telnet class used in the program are explained below.

  1. Telnet.read_until - Read until a given string, expected, is encountered or until timeout seconds have passed.

  2. Telnet.write - Write a string to the socket, doubling any IAC characters. This can block if the connection is blocked. May raise socket.error if the connection is closed.

  3. Telnet.read_all() - Read all data until EOF; block until connection closed.

Example

import getpass
import telnetlib

HOST = "http://localhost:8000/"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("ls\n")
tn.write("exit\n")

print tn.read_all()

当我们运行以上程序时,我们得到以下输出:

When we run the above program, we get the following output −

 - lrwxrwxrwx    1 0        0               1 Nov 13  2012 ftp -> .
- lrwxrwxrwx    1 0        0               3 Nov 13  2012 mirror -> pub
- drwxr-xr-x   23 0        0            4096 Nov 27  2017 pub
- drwxr-sr-x   88 0        450          4096 May 04 19:30 site
- drwxr-xr-x    9 0        0            4096 Jan 23  2014 vol

请注意,此输出特定于在运行程序时提交其详细信息的远程计算机。

Please note that this output is specific to the remote computer whose details are submitted when the program is run.