所以我有两个文件:一个Python文件,它基本上暴力破解字符列表中的每个组合,以及一个批处理文件,用作锁来查看“Python文件是否会暴力破解它”。当在CMD中运行时
python "C:\Users\alexe\OneDrive\Documents\test file\brute_forcer.py" | cmd /C "C:\Users\alexe\OneDrive\Documents\test file\lock1.bat"
,它返回错误
Traceback (most recent call last):
File "C:\Users\alexe\OneDrive\Documents\test file\brute_forcer.py", line 10, in <module>
print(x)
BrokenPipeError: [Errno 32] Broken pipe
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='cp1252'>
OSError: [Errno 22] Invalid argument
文件 brute_forcer:
import itertools
def foo(l):
for i in range(1, 101):
yield from itertools.product(*([l] * i))
for x in foo('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()[]{},.<>?|;:`~'):
#print("y")
x = ''.join(x)
print(x)
和lock1.bat文件:
@echo off
setlocal enabledelayedexpansion
set "correct_password=HEL"
:INPUT
set /p "user_input=Enter the password: "
if "%user_input%"=="%correct_password%" (
echo Correct password entered. Access granted.
goto :EOF
) else (
echo Incorrect password. Try again.
goto INPUT
)
我尝试让 AI 看看它会做什么,但这根本没有帮助,也没有解决我的问题。
这比简单地将 python 脚本的输出通过管道传输到批处理文件中更复杂,因为存在连续交互。
如果你尝试运行类似
python3 brute_forcer.py | lock1.bat
的东西,我相信它会在Python完成后将Python脚本的所有输出立即重定向到批处理文件。
然而,我们需要的是在Python执行过程中不断地向批处理文件提供输入并读取输出。为此,我们需要 subprocess 模块。 brute_forcer.py(如果你想输出 python 脚本正在执行的所有操作,我将调试打印语句保留为注释):
import itertools
from subprocess import Popen, PIPE, STDOUT
def foo(l):
for i in range(1, 101):
yield from itertools.product(*([l] * i))
p = Popen(['l.bat'], stdout=PIPE, stdin=PIPE, stderr=STDOUT, text=True)
result = p.stdout.readline()
# print(result)
print("Brute forcing...")
for x in foo('#ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()[]{},.<>?|;:`~'):
guess = ''.join(x).strip()
# print("trying: %s " %(guess))
p.stdin.write(guess)
p.stdin.flush()
result = p.stdout.readline()
# print(result)
if ("Correct" in result):
print("Password found: %s " %(guess))
break
if ("Incorrect" in result):
result = p.stdout.readline()
# print(result)
我还更改了批处理文件以在提示输入时打印换行符,否则python中的readline()函数将无法工作,并且读取不以换行符结尾的任意长输入会稍微复杂一些。
lock1.bat:
@echo off
setlocal enabledelayedexpansion
set "correct_password=HEL"
:INPUT
echo Enter the password:
set /p user_input=
if "%user_input%"=="%correct_password%" (
echo Correct password entered. Access granted.
goto :EOF
) else (
echo Incorrect password. Try again.
goto INPUT
)