• threading实例


    import paramiko, threading
    import queue
    import pymysql
    
    
    class ThreadPool(object):
        def __init__(self, maxsize):
            self.maxsize = maxsize
            self._q = queue.Queue(self.maxsize)
            for i in range(self.maxsize):
                self._q.put(threading.Thread)
    
        def getThread(self):
            return self._q.get()
    
        def addThread(self):
            self._q.put(threading.Thread)
    
    
    def ssh_fun(ip, user, password, pool, db):
        cursor = db.cursor()
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(ip, 22, user, password)
            stdin, stdout, stderr = ssh.exec_command('hostname')
            info = stdout.read().decode().strip()
            print('IP:%s  hostname:%s' % (ip, info))
            try:
                cursor.execute(
                    'insert into server_status(ip,password,hostname) values ("%s","%s","%s")' % (ip, password, info))
                db.commit()
            except:
                db.rollback()
            ssh.close()
        except Exception:
            print('sorry I can`t connect this server [%s]' % ip)
        pool.addThread()
    
    
    if __name__ == '__main__':
        t_list = []
        pool = ThreadPool(3)
        db = pymysql.connect('192.168.32.188', 'hjc', '111111', 'hjc')
        with open('aaa', 'r+', encoding='utf-8') as f:
            for line in f:
                split = line.split()
                ip, user, password = split[0], split[1], split[2]
                th = pool.getThread()
                t = th(target=ssh_fun, args=(ip, user, password, pool, db))
                t.start()
                t_list.append(t)
        for i in t_list:
            i.join()
        db.close()
    

      

  • 相关阅读:
    正则表达式 1
    14 同步 1
    14 线程属性
    14 线程状态
    14 线程
    window.location.hostname与 window.location.host 区别
    泛型 的通配符类型 extends super
    svn拷贝一个项目作为新项目
    List Collections sort
    && 和 || 逻辑运算符
  • 原文地址:https://www.cnblogs.com/yoyo1216/p/10129773.html
Copyright © 2020-2023  润新知