【发布时间】:2018-10-18 18:59:44
【问题描述】:
我正在为我的班级编写一个脚本来打开受密码保护的 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()
【问题讨论】:
-
看起来在
zip_ref.setpassword(b'passattempt')中您将passattempt作为字符串传递。试试zip_ref.setpassword(passattempt) -
我之前尝试过,但后来我收到一个错误,指出该项目是一个字符串,应该是二进制的,所以我必须使用 b('passattemp')。当我使用像这样的 zip_ref.setpassword(b'12345') 测试文件和密码时,它会完美地打开 zip 文件。
-
好的,您只需要创建另一个变量并将
passattempt以二进制形式存储在其中,然后将其传递给zip_ref。您可以使用bin_a = bin(a)进行转换
标签: python password-protection zipfile