2013-08-22 90 views
4

我需要構建一個腳本來獲取儘可能多的主機的telnet輸出,並將它們保存到每個主機的單獨文件中。腳本應該作爲守護進程運行。Python多個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

+0

聽起來不錯,謝謝! – danidelvalle

+2

一個想法:使用select() – ReyCharles

回答

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

希望這會有所幫助,如果您有任何問題,更新您的問題或發表評論。