Python使用paramiko进行远程交互

import sys, getopt
import paramiko,socket
import Queue
import threading
import time
import operator
import re
from bcolors import bcolors


servers = open("").readlines()
servers = [s.strip() for s in servers]
validServerNum = len(servers)
sevnumLock = threading.Lock()

serverQueue = Queue.Queue()
serverLock = threading.Lock()

loadSum = {}
loadLock = threading.Lock()

optargs = sys.argv[1:]
paramiko.util.log_to_file('paramiko.log')
try:
    opts, args = getopt.getopt(optargs, "s:n:", ["sample=", "number="])
except getopt.GetoptError as err:
    sys.stderr.write("[ERROR] Invalid Syntax\n")
    sys.exit(1)


for opt, arg in  opts:
    if opt in ("-s", "--sample="):
        stimes = int(arg)
    elif opt in ("-n", "--number="):
        number = int(arg)


if not locals().has_key("stimes"):
    stimes = 3

if not locals().has_key("number"):
    number = len(servers)
        

class ThreadSniffer(threading.Thread):
    def __init__(self, queue, threadID, stimes, loadsum):
        threading.Thread.__init__(self)
        self.queue = queue
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.id = threadID
        self.stimes = stimes
        self.loadsum = loadsum        

    def run(self):
        global validServerNum
        while not self.queue.empty():
            serverLock.acquire()
            server = self.queue.get()
            serverLock.release()

            print "#"+str(self.id)+" thread trys to connect to server "+server
            try:
                self.ssh.connect(server, username="hnie")
                loadtime = [0, 0, 0]
                loadbase = [0, 0, 0]
                for stime in range(1, self.stimes+1):
                    sin, sout, serr = self.ssh.exec_command("uptime")
                    res = sout.readlines()[0].split()[-3:]
                    res = [float(r.rstrip(',')) for r in res]
                    for i in range(len(res)):
                        loadtime[i] += stime*res[i]
                        loadbase[i] += stime
                    time.sleep(1)    
                self.ssh.close()
                
                for i in range(len(loadtime)):
                    loadtime[i] /= loadbase[i]
                loadLock.acquire()
                self.loadsum[server]=loadtime
                loadLock.release()
                
            except paramiko.AuthenticationException:
                sevnumLock.acquire()
                validServerNum -= 1
                sevnumLock.release()
            except socket.gaierror:
                sevnumLock.acquire()
                validServerNum -= 1
                sevnumLock.release()               
                print bcolors.WARNING+"we do not have "+server+bcolors.ENDC
            except paramiko.ssh_exception.NoValidConnectionsError:
                sevnumLock.acquire()
                validServerNum -= 1
                sevnumLock.release()               
                print bcolors.WARNING+"we cannot connect to  "+server+bcolors.ENDC
            except paramiko.ssh_exception.SSHException:
                sevnumLock.acquire()
                validServerNum -= 1
                sevnumLock.release()               
                print bcolors.WARNING+"Error reading SSH protocol banner for "+server+bcolors.ENDC
            except socket.error, exc:
                sevnumLock.acquire()
                validServerNum -= 1
                sevnumLock.release()               
                print bcolors.FAIL+str(exc)+"!!!There may no longer exist "+server+bcolors.ENDC
                
            self.queue.task_done()


for server in servers:
    serverQueue.put(server)            
numThread = max(len(servers)/4, 20)

for n in range(numThread):
    threadS = ThreadSniffer(serverQueue, n, stimes, loadSum)
    threadS.setDaemon(True)
    threadS.start()

serverQueue.join()
loadSum = sorted(loadSum.items(), key=operator.itemgetter(1))
number = min(number, validServerNum)

for n in range(number):
    print (loadSum[n][0]+"\t"+"\t".join(map(str, loadSum[n][1])))

你可能感兴趣的:(Python)