【问题标题】:using a variable with the ZipFile.setpassword command通过 ZipFile.setpassword 命令使用变量
【发布时间】: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


【解决方案1】:

是的,只需使用 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

【讨论】:

  • 感谢您的确认。我继续研究它,发现与发布时间相同。我终于让它工作了,呜呼!!
猜你喜欢
  • 2018-11-18
  • 1970-01-01
  • 2019-08-03
  • 2012-11-02
  • 2020-10-10
  • 2013-01-10
  • 2023-04-05
  • 2020-03-28
  • 1970-01-01
相关资源
最近更新 更多