Python 远程登录客户端

Python telnet client

大家好!

我目前正在尝试使用 Python 2.7 的 Telnetlib (https://docs.python.org/2/library/telnetlib.html) 与一些外部设备进行通信。

我已经设置了基础:

import sys
import telnetlib
tn_ip = xxxx
tn_port = xxxx
tn_username = xxxxx
tn_password = xxxx

searchfor = "Specificdata"

def telnet():
    try:
        tn = telnetlib.Telnet(tn, tn, 15)
        tn.set_debuglevel(100)
        tn.read_until("login: ")
        tn.write(tn_username + "\n")
        tn.read_until("Password: ")
        tn.write(tn_password + "\n")
        tn.read_until(searchfor)
        print "Found it!"
    except:
        print "Unable to connect to Telnet server: " + tn_ip

telnet()

我正在尝试查看它输出的所有数据(相当多),直到找到我需要的数据。虽然它登录得很好,甚至找到了我正在寻找的数据,并打印了我找到它的消息,但我正在尝试一种方法来保持与 telnet 的连接打开,因为可能还有其他数据(或重复数据) ) 如果我注销并重新登录,我会失踪。

有人知道怎么做吗?

好像您想连接到外部设备一次并在每次看到特定字符串时打印一条消息。

import sys
import telnetlib
tn_ip = "0.0.0.0"
tn_port = "23"
tn_username = "xxxxx"
tn_password = "xxxx"

searchfor = "Specificdata"


def telnet():
    try:
        tn = telnetlib.Telnet(tn_ip, tn_port, 15)
    except:
        print "Unable to connect to Telnet server: " + tn_ip
        return
    tn.set_debuglevel(100)
    tn.read_until("login: ")
    tn.write(tn_username + "\n")
    tn.read_until("Password: ")
    tn.write(tn_password + "\n")
    while True:
        tn.read_until(searchfor)
        print "Found it"

telnet()