zoukankan      html  css  js  c++  java
  • 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()
    

      

  • 相关阅读:
    uva 147 Dollars
    hdu 2069 Coin Change(完全背包)
    hdu 1708 Fibonacci String
    hdu 1568 Fibonacci
    hdu 1316 How Many Fibs?
    poj 1958 Strange Towers of Hanoi
    poj 3601Tower of Hanoi
    poj 3572 Hanoi Tower
    poj 1920 Towers of Hanoi
    筛选法——素数打表
  • 原文地址:https://www.cnblogs.com/yoyo1216/p/10129773.html
Copyright © 2011-2022 走看看