Python multiple telnet sessions

后端 未结 1 1064
情书的邮戳
情书的邮戳 2021-01-19 06:45

I need to build a script to get the telnet output of as many hosts as possible and save them to a separate file for each host. The script should run as a daemon.

Fo

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-19 06:56

    I believe the following should do what your require, I took your original code and made it into a type of thread:

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

    Hope this helps, if you have any problem update your question or leave a comment.

    0 讨论(0)
提交回复
热议问题