Python多个telnet会话

4
我需要编写一个脚本,以获取尽可能多的主机的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

1
你可以尝试使用多线程吗?在一个主要受网络时间限制的应用程序中,GIL作为瓶颈应该是完全可以忽略的,而线程更加轻量级。 - Phoshi
2
一个想法:使用select()。 - ReyCharles
1个回答

4
我相信以下内容可以满足你的需求,我将你原来的代码改为了线程类型:

我相信以下内容可以满足你的需求,我将你原来的代码改为了线程类型:

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()

希望这能帮到你,如果有任何问题,请更新你的问题或留下评论。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接