2014-09-29 39 views
0

我想從telnet輸出到主機找到一個字符串(例如:ZNTS)。搜索整個telnet輸出結果,同時做並行telnet到多個網絡設備

我想同時telnet到多個主機,因爲等待從主機到主機完成需要很長時間。主機響應速度不夠快,所以我需要在每個命令行之後休眠。

下面是我的代碼:

import sys 
import telnetlib 
import time 

MXK_LIST = ['172.16.32.15', 
     '172.16.33.30', 
     '192.168.55.3', 
     '192.168.52.3', 
     '192.168.54.3', 
     '192.168.42.25', 
     '192.168.43.3', 
     '192.168.44.3', 
     '192.168.45.3', 
     '192.168.46.3', 
     '192.168.47.3', 
     '192.168.48.3', 
     '192.168.49.9'] 

TOTAL_MXK = len(MXK_LIST) 

ZNTS = str(sys.argv[1]) 
DEBUG = str(sys.argv[2]) 

username = "admin" 
password = "4n0cmek0n9net" 

I = 0 
C = 0 
print "\n Finding ZNTS = " + ZNTS 
print "\n It will take around 5 minutes to complete the searching !!\n" 

for MXK in MXK_LIST: 
    I = I + 1 
    OUTPUT = "" 
    try: 
     tn = telnetlib.Telnet(MXK) 
    except: 
     print "Bad Connection. Please verify IP again." 
     sys.exit(0) 
    tn.read_until(b"login: ",1) 
    tn.write(username + "\n") 
    time.sleep(5) 
    tn.read_until(b"password: ",1) 
    tn.write(password + "\n") 
    time.sleep(5) 
    OUTPUT = tn.read_until(b">",1) 
    if DEBUG == 1: print OUTPUT 
    time.sleep(5) 
    tn.write("onu showall 1" + "\n") 
    time.sleep(5) 
    tn.read_until(b"[no] ",1) 
    tn.write(b"yes" + "\n") 
    time.sleep(15) 
    OUTPUT = tn.read_until(b"quit",1) 
    time.sleep(5) 
    if DEBUG == 1: print OUTPUT 
    tn.write("A" + "\n") 
    time.sleep(5) 
    OUTPUT = tn.read_until(b">",1) 
    if DEBUG == 1: print OUTPUT 
    tn.write("exit\n") 
    if ZNTS in OUTPUT: 
      print str(I) + "/" + str(TOTAL_MXK) + " : FOUND " + ZNTS + " IN " + MXK 
      C = C + 1 
    else: 
      print str(I) + "/" + str(TOTAL_MXK) + " : NOT FOUND " + ZNTS + " IN " + MXK 
    print "\n"+ZNTS + " is found in " + str(C) + " MXK"  
+0

歡迎StackOverflow上。你沒有提出問題或清楚解釋你的問題,因此讀者不能很快看到他們是否可以幫助你。 – Kilazur 2014-09-29 09:55:43

回答

0

您可以嘗試產卵每個telnet會話線程以及並行搜索的方式。

退房這裏的多線程代碼示例:

http://stackoverflow.com/questions/6286235/multiple-threads-in-python 
相關問題