threading实例

时间:2025-02-05 18:34:08
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()