Python telnet连接失败

Python telnet connection failure

我有接受 telnet 连接的设备,可以通过 AT 命令使用它

这是我的代码,我相信应该很简单,但由于某种原因它不会工作我对 telnet lib 还很陌生,所以我不明白我在这里遗漏了什么

def connect(self, host, port):
    try:
        Telnet.open(host, port)
        Telnet.write('AT'+"\r")
        if Telnet.read_until("OK"):
            print("You are connected")
    except:
        print("Connection cannot be established")

它总是命中例外。

当我尝试导入 telnetlib 并且 运行 它只是使用没有端口的 IP 时,我也遇到了以下错误。

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
Telnet.open('192.168.0.1')
TypeError: unbound method open() must be called with Telnet instance as 
first argument (got str instance instead)

我无法理解它要我做什么。

需要调用 Telnet class 的构造函数:

import traceback

def connect(self, host, port):
    try:
        telnet_obj = Telnet(host, port) # Use the constructor instead of the open() method.
    except Exception as e: # Should explicitly list exceptions to be caught. Also, only include the minimum code where you can handle the error.
        print("Connection cannot be established")
        traceback.print_exc() # Get a traceback of the error.
        # Do further error handling here and return/reraise.

    # This code is unrelated to opening a connection, so your error
    # handler for establishing a connection should not be run if
    # write() or read_until() raise an error.
    telnet_obj.write('AT'+"\r") # then use the returned object's methods.
    if telnet_obj.read_until("OK"):
        print("You are connected")

相关:Python newbie having a problem using classes