创建一个多会话 Telnet 日志记录器可以实现对多个 Telnet 会话进行连接、监控和记录日志。以下是一个基本的 Python 示例,使用 telnetlib
库来实现多会话 Telnet 日志记录器,并使用 threading
模块来处理多个会话。
1、问题背景
我们需要编写一个脚本,以便尽可能多地获取主机 Telnet 输出,并将它们保存到每个主机的单独文件中。该脚本应作为守护进程运行。目前,我们有一个函数封装逻辑,可以使用 telnetlib 为单个主机执行此操作,但我们不知道如何继续。我们计划为每个主机打开一个进程(multiprocessing.Process),但我们怀疑这会浪费资源,并且肯定有更好的方法 :)
2、解决方案
您可以使用以下代码来解决这个问题:
这个脚本将创建一个监听器类,该类将继承自 threading.Thread
类。监听器类将具有一个名为 run()
的方法,该方法将连接到 Telnet 主机,然后开始一个无限循环,该循环将读取来自 Telnet 主机的输出并将其写入文件。
然后,脚本将创建一个名为 things_to_listen_to
的字典,该字典将包含要监听的主机及其相应的输出文件。脚本还将创建一个名为 thread_holder
的列表,该列表将包含所有已创建的监听器线程。
最后,脚本将遍历 things_to_listen_to
字典中的每个项目,并为每个项目创建一个监听器线程。然后,脚本将启动所有监听器线程,并让它们无限期地运行。
上面示例展示了如何使用 telnetlib3
和 asyncio
来处理 Telnet 连接,并使用 threading
来处理多个会话。每个 TelnetLogger
实例在一个单独的线程中运行,以实现多会话并行处理。