创建一个多会话 Telnet 日志记录器可以实现对多个 Telnet 会话进行连接、监控和记录日志。以下是一个基本的 Python 示例,使用 telnetlib
库来实现多会话 Telnet 日志记录器,并使用 threading
模块来处理多个会话。
1、问题背景
我们需要编写一个脚本,以便尽可能多地获取主机 Telnet 输出,并将它们保存到每个主机的单独文件中。该脚本应作为守护进程运行。目前,我们有一个函数封装逻辑,可以使用 telnetlib 为单个主机执行此操作,但我们不知道如何继续。我们计划为每个主机打开一个进程(multiprocessing.Process),但我们怀疑这会浪费资源,并且肯定有更好的方法 😃
def TelnetLogSaver(hostname, ip, filename):
# open files and telnet sessions
f = open(filename, "a")
tn = telnetlib.Telnet(ip, 23, TIMEOUT)
# login
e = tn.read_until("Login: ")
tn.write(USER + "\n")
# and password
e = tn.read_until("Password: ")
tn.write(PASSWORD + "\n")
# Connected. Start infinite loop to save messages log
while True:
e = tn.read_until(PROMPT, TIMEOUT)
if e is not "":
f.write(datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))
f.write(e)
f.flush()
# avoid session timeout
tn.write("\n")
e = tn.read_until(PROMPT)
2、解决方案
您可以使用以下代码来解决这个问题:
import threading
import telnetlib
import datetime
import sys
# Global Variable Declarations
TIMEOUT = 30
USER = "Noel"
PROMPT = "Noel"
class listener(threading.Thread):
def __init__(self, filename, ip):
# Have to make a call to the super classes' __init__ method
super(listener, self).__init__()
self.f = open(filename, "a")
try:
self.tn = telnetlib.Telnet(ip, 23, TIMEOUT)
except:
print("Bad Connection")
sys.exit(0)
def run(self):
# login
e = self.tn.read_until("Login: ")
self.tn.write(USER + "\n")
# and password
e = self.tn.read_until("Password: ")
self.tn.write(PASSWORD + "\n")
while True:
e = self.tn.read_until(PROMPT, TIMEOUT)
if e is not "":
self.f.write(datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))
self.f.write(e.strip())
self.f.flush()
# avoid session timeout
self.tn.write("\n")
if __name__ == "__main__":
# Things to listen to is a dictionary of hosts and files to output
# to, to add more things to listen to just add an extra entry into
# the things_to_listen_to in the format: host : outputfile
things_to_listen_to = {"localhost": "localhost_output.txt"}
# Thread holder is going to hold all the threads we are going to start
thread_holder = []
for host, file in things_to_listen_to.iteritems():
thread_holder.append(listener(file, host))
for thread in thread_holder:
thread.run()
这个脚本将创建一个监听器类,该类将继承自 threading.Thread
类。监听器类将具有一个名为 run()
的方法,该方法将连接到 Telnet 主机,然后开始一个无限循环,该循环将读取来自 Telnet 主机的输出并将其写入文件。
然后,脚本将创建一个名为 things_to_listen_to
的字典,该字典将包含要监听的主机及其相应的输出文件。脚本还将创建一个名为 thread_holder
的列表,该列表将包含所有已创建的监听器线程。
最后,脚本将遍历 things_to_listen_to
字典中的每个项目,并为每个项目创建一个监听器线程。然后,脚本将启动所有监听器线程,并让它们无限期地运行。
上面示例展示了如何使用 telnetlib3
和 asyncio
来处理 Telnet 连接,并使用 threading
来处理多个会话。每个 TelnetLogger
实例在一个单独的线程中运行,以实现多会话并行处理。