【问题标题】:python logging framework with telnet read_all function带有 telnet read_all 功能的 python 日志框架
【发布时间】:2018-02-04 10:53:06
【问题描述】:

我是 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

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

【问题讨论】:

    标签: python python-2.7 logging telnet


    【解决方案1】:

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

    Python 从最内层到最外层执行函数或方法调用。所以代码如下: 记录信息(telnet.read_all()) 真的在做: return_value = telnet.read_all() 记录信息(返回值) (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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-18
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2012-09-07
      相关资源
      最近更新 更多