前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >多会话 Telnet 日志记录器

多会话 Telnet 日志记录器

原创
作者头像
华科云商小徐
发布2024-07-10 09:27:43
1090
发布2024-07-10 09:27:43
举报
文章被收录于专栏:小徐学爬虫

创建一个多会话 Telnet 日志记录器可以实现对多个 Telnet 会话进行连接、监控和记录日志。以下是一个基本的 Python 示例,使用 telnetlib 库来实现多会话 Telnet 日志记录器,并使用 threading 模块来处理多个会话。

1、问题背景

我们需要编写一个脚本,以便尽可能多地获取主机 Telnet 输出,并将它们保存到每个主机的单独文件中。该脚本应作为守护进程运行。目前,我们有一个函数封装逻辑,可以使用 telnetlib 为单个主机执行此操作,但我们不知道如何继续。我们计划为每个主机打开一个进程(multiprocessing.Process),但我们怀疑这会浪费资源,并且肯定有更好的方法 :)

代码语言:javascript
复制
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、解决方案

您可以使用以下代码来解决这个问题:

代码语言:javascript
复制
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 字典中的每个项目,并为每个项目创建一个监听器线程。然后,脚本将启动所有监听器线程,并让它们无限期地运行。

上面示例展示了如何使用 telnetlib3asyncio 来处理 Telnet 连接,并使用 threading 来处理多个会话。每个 TelnetLogger 实例在一个单独的线程中运行,以实现多会话并行处理。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档