我正在使用 ProcessPoolExecutor 编写一个简单的强力函数。任务是找到 8 位密码的匹配哈希值。
我注意到一个问题,如果找到所有给定的密码,该函数仍然会循环。
我尝试实现一个全局计数器变量,但我很快意识到,它不在期货之间共享。有什么方法可以创建一个计数器或者其他所有进程都知道的东西来缩短执行时间?
这是我的执行经理:
def brute_force_password() -> None:
futures = []
with ProcessPoolExecutor(multiprocessing.cpu_count()) as executor:
for interval in range(len(PASSWORDS_TO_BRUTE_FORCE)):
futures.append(
executor.submit(
check_password_in_interval,
interval * 1_000_0000,
(interval + 1) * 1_000_0000
)
)
wait(futures)
以及循环检查功能:
def check_password_in_interval(start: int, end: int) -> None:
for guess in range(start, end):
guess = f"{guess:08d}"
hashed_guess = sha256_hash_str(guess)
if hashed_guess in PASSWORDS_TO_BRUTE_FORCE:
index = PASSWORDS_TO_BRUTE_FORCE.index(hashed_guess)
HACKED_PASSWORDS[index] = guess
print(f"{hashed_guess} is {guess}.")
非常感谢您的时间和帮助!
我尝试过的:全局变量和环境变量
您可以尝试使用多处理,它允许您跨进程共享值:
import multiprocessing
from concurrent.futures import ProcessPoolExecutor, wait
from ctypes import c_int
def brute_force_password(passwords_found: multiprocessing.Value) -> None:
futures = []
with ProcessPoolExecutor(multiprocessing.cpu_count()) as executor:
for interval in range(len(PASSWORDS_TO_BRUTE_FORCE)):
futures.append(
executor.submit(
check_password_in_interval,
interval * 1_000_0000,
(interval + 1) * 1_000_0000,
passwords_found
)
)
wait(futures)
def check_password_in_interval(start: int, end: int, passwords_found: multiprocessing.Value) -> None:
for guess in range(start, end):
guess = f"{guess:08d}"
hashed_guess = sha256_hash_str(guess)
if hashed_guess in PASSWORDS_TO_BRUTE_FORCE:
with passwords_found.get_lock():
index = PASSWORDS_TO_BRUTE_FORCE.index(hashed_guess)
HACKED_PASSWORDS[index] = guess
passwords_found.value += 1
print(f"{hashed_guess} is {guess}.")
if passwords_found.value == len(PASSWORDS_TO_BRUTE_FORCE):
return
if __name__ == '__main__':
passwords_found = multiprocessing.Value(c_int, 0)
brute_force_password(passwords_found)