线程处理批量问题
import threading
import time
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
class IPThread(threading.Thread):
def __init__(self,cmd,hostname,port=22,user='root'):
super(IPThread, self).__init__()
self.cmd=cmd
self.hostname=hostname
self.port=port
self.user=user
def conn(self):
# ssh root@172.25.254.250
# 创建一个ssh对象;
client = paramiko.SSHClient()
# 返回一个私钥对象
private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
# 2. 解决问题:如果之前没有;连接过的ip, 会出现
# Are you sure you want to continue connecting (yes/no)? yes
# 自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 3. 连接服务器
client.connect(hostname=self.hostname,
port=self.port,
username=self.user,
pkey=private_key
)
# 4. 执行操作
stdin, stdout, stderr = client.exec_command(self.cmd)
except NoValidConnectionsError as e:
print("连接%s失败"%(self.hostname))
except AuthenticationException as e:
print("%s密码错误"%(self.hostname))
else:
# 5. 获取命令的执行结果;
result = stdout.read().decode('utf-8')
print(result)
finally:
# 6. 关闭连接
client.close()
def main():
#用来储存所有的线程对象
start_time = time.time()
threads=[]
for count in range(254):
host='172.25.254.%s' %(count+1)
t=IPThread(cmd='hostname',hostname=host)
threads.append(t)
t.start()
#join方法,等待所有的子线程结束后执行结束
[thread.join() for thread in threads]
print('任务执行结束,执行时间为%s'%(time.time()-start_time))
if __name__ == '__main__':
main()
计算1~100000之间所有素数和, 要求如下:
- 编写函数判断一个数字是否为素数,
- 使用内置函数sum()统计所有素数和。
- 对比1: 对比使用多进程和不使用多进程两种方法的速度。
- 对比2:对比开启4个多进程和开启10个多进程两种方法的速度
from math import sqrt
import multiprocessing
from mytime import timeit
# def sum_prime():
# res = [p for p in range(2, 100000) if 0 not in
# [p % d for d in range(2, int(sqrt(p)) + 1)]]
#
# sum(res)
def sum_prime():
primelist=[]
for i in range(2,100000):
for j in range(2, i):
if i % j == 0:
break
else:
primelist.append(i)
sum(primelist)
@timeit
def has_process_4():
processes = []
for i in range(4):
p = multiprocessing.Process(target=sum_prime())
processes.append(p)
p.start()
[process.join() for process in processes]
@timeit
def no_has_process():
sum_prime()
@timeit
def has_process_10():
processes = []
for i in range(10):
p = multiprocessing.Process(target=sum_prime())
processes.append(p)
p.start()
[process.join() for process in processes]
if __name__ == '__main__':
has_process_4()
no_has_process()
# has_process_10()