带有telnet read_all函数的python日志框架

时间:2017-08-26 16:26:54

标签: python python-2.7 logging telnet

我是Python的菜鸟,我正在尝试使用telnel.read_all函数捕获设备日志。我正在使用python的日志框架来实现此目的。 如果我尝试执行以下操作,代码会挂起:     logging.info(telnet.read_all())

def telNetCallInitial():
 host  = "5.35.8.24"
 user  = "lab"
 password = "lab"
 telnet  = telnetlib.Telnet(host)
 telnet.read_until('Username: ', 3)
 telnet.write(user + '\r')
 telnet.read_until('Password: ', 3)
 telnet.write(password + '\r')
 telnet.write('enable' + '\r\n')
 telnet.write('enable_password' + '\r\n')
 logging.info(telnet.read_all())
 logging.info("inside telnet call initial")
 return telnet

但这不起作用,程序挂起。 对此有任何想法。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您遇到此问题是因为read_all()是一个阻塞函数调用。也就是说,在telnet连接关闭之前它不会返回(这是一个eof或文件的结尾)。

Python执行从最里面到最外面的函数或方法调用。所以代码如下:     logging.info(telnet.read_all()) 真的在做:     return_value = telnet.read_all()     logging.info(RETURN_VALUE) (return_value只是表示解释器将每次调用的结果传递给它之外的调用)。

对此的解决方案是使用不阻止的调用,可能类似于:

import telnet
import logging
import time

def prepare_connection(host, user, password):
    instance  = telnetlib.Telnet(host)
    instance.read_until('Username: ', 3)
    instance.write(user + '\r')
    instance.read_until('Password: ', 3)
    instance.write(password + '\r')
    instance.write('enable' + '\r\n')
    instance.write('enable_password' + '\r\n')
    # at this point, the connection is prepared so we can return the telnet object
    logging.info("*** Telnet connection prepared")
    return instance

def log_output(telnet_instance):
    """Given a connected telnet instance, sends all data received over it to logging.info."""
    running = True
    while running == True:
        try:
            data = telnet_instance.read_very_eager()
            logging.info(data)
            time.sleep(0.1) # sleep for 100 ms so we don't try too often to read data (read_very_eager won't block,
              # so without this CPU usage would spike)
        except EOFError as e:
            logging.info("*** telnet connection closed")
            running = False

if __name__ == '__main__':
    con = prepare_connection(host="5.35.8.24", user="lab", password="lab")
    log_output(con)