我正在为我的班级准备一个脚本,以打开一个受密码保护的zip文件。我有需要循环输入的密码列表。
我创建了一个脚本,当我在密码字段中手动输入密码时,该脚本可以完美执行该功能:ZipFile.setpassword(b'12345')
但是我想做的是使用变量passwordattempt代替它,因为它遍历列表的每个条目,例如ZipFile.setpassword(b'passwordattempt')。使用分配给变量的密码。
通过使用print(passattempt),我可以看到它正在正确浏览我的列表
#################################
## Create a temp list of pass ##
## words from the allpass.txt ##
## file ##
#################################
#Create a temp Library
passwordlib = []
#Open temp allpassword file to put into temp list
with open('allpass.txt', 'r+') as f:
for line in f:
line = line.rstrip("\n")
#print(line)
passwordlib.append(line)
f.close()
#End of temp list creation
#Attempt to open zip file using the list of passwords in passwordlib[]
for line in passwordlib:
passattempt = line.strip('\n')
try:
zip_ref = zipfile.ZipFile("Resources/ZippedFiles/testzip.zip", 'r')
print (passattempt) #Print to confirm passwords are cycling through
zip_ref.setpassword(b'passattempt')
zip_ref.extractall("Resources/ZippedFiles/testout/")
except:
pass #if password is incorrect, ignore Runtime error and move to next password
zip_ref.close()
答案 0 :(得分:0)
是的,只需使用encode
使用默认编码(utf-8)将string
转换为bytes
。
import zipfile
with open('allpass.txt', 'r+') as f:
passwordlib = f.readlines()
# Attempt to open zip file using the list of passwords in passwordlib[]
for line in passwordlib:
passattempt = line.strip('\n')
with zipfile.ZipFile("file.zip", 'r') as zf:
print(passattempt) # Print to confirm passwords are cycling through
zf.setpassword(passattempt.encode())
try:
zf.extractall("Resources/ZippedFiles/testout/")
except RuntimeError as e:
if 'Bad password' not in str(e):
raise