ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python多个telnet会话

2019-06-24 23:46:30  阅读:266  来源: 互联网

标签:python telnet telnetlib


我需要构建一个脚本来获取尽可能多的主机的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

解决方法:

我相信以下内容应该满足您的要求,我将您的原始代码转换为一种线程:

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

希望这有帮助,如果您有任何问题更新您的问题或发表评论.

标签:python,telnet,telnetlib
来源: https://codeday.me/bug/20190624/1282718.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有