#!/usr/bin/python2.6 import os import time import paramiko import ConfigParser import threading import Queue import optparse class thread_ssh(threading.Thread): def __init__(self,work_queue): super(thread_ssh,self).__init__() self.work_queue = work_queue def run(self): while True: try: machine = self.work_queue.get() self.process(machine) finally: self.work_queue.task_done() def process(self,machine): hostname=str(machine[1]).strip() port=int(machine[2]) username=str(machine[3]).strip() password=str(machine[4]).strip() cmd=';'.join( machine[5:]) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.load_system_host_keys() #ssh.load_host_keys('/root/.ssh/known_hosts') ssh.connect(hostname,port,username,password) (stdin,stdout,stderr)=ssh.exec_command(cmd) output=stdout.read() pid=os.getpid() print "The %s run in %s" %(self.name,hostname) print output info.write('n=======================n====>>'+hostname+'n=======================nn') info.write(output) info.flush() ssh.close() def read_cfg_file(file): machines = [] config = ConfigParser.ConfigParser() config.read(file) host_items = config.items("HOST") cmd_items = config.items("CMD") for item in host_items: host=item[1].split() for cmd_item in cmd_items: host.append(cmd_item[1]) machines.append(host) return machines def parse_options(): description = "A ssh client with thread." usage="usage: %prog [options]n Please use --helpnnAuthor: mrmuxl@sina.com" version = "Version: %prog 0.1 nAuthor: mrmuxl@sina.com" parser = optparse.OptionParser(description = (description),usage = (usage),version=(version)) parser.add_option("-c","--config",action="store",type="string",dest="config",default="pssh.cfg",help="program's config file") parser.add_option("-o","--outpufile",action="store",type="string",dest="outputfile",default="outputfile.log",help="program's output file") parser.add_option("-l","--logfile",action="store",type="string",dest="logfile",default="ssh.log",help="ssh client running log") opts,args=parser.parse_args() return opts,args if __name__ == '__main__': start_cpu = time.clock() start_real = time.time() opts,args = parse_options() paramiko.util.log_to_file(opts.logfile) info=open(opts.outputfile,'a') hosts=read_cfg_file(opts.config) work_queue = Queue.Queue() for i in range(9): pssh =thread_ssh(work_queue) pssh.daemon=True pssh.start() for machine in hosts: if machine[0] == 'On' or machine[0] == 'on' or machine[0] == 'ON': work_queue.put(machine) work_queue.join() info.close() end_cpu = time.clock() end_real = time.time() print("%f Real Seconds" % (end_real - start_real)) print("%f CPU Seconds" % (end_cpu - start_cpu)) |
这是我写的唉!代码里面还有我的邮箱啊!
本文由 chen 整编,转载请注明来自 运维技术 – HackRoad.com!
参考来源:blog.csdn.net
文章底部有您博客链接,如有侵权,请告知,我删除。