Python破解ZIP或RAR文件密码

基本原理在于Python标准库zipfile和扩展库unrar提供的解压缩方法extractall()可以指定密码,这样的话首先(手动或用程序)生成一个字典,然后依次尝试其中的密码,如果能够正常解压缩则表示密码正确。

import os

import sys

#zipfile是Python标准库

import zipfile

#尝试导入扩展库unrar,如果没有就临时安装

try:

    from unrar import rarfile

except:

    path = '"'+os.path.dirname(sys.executable)+'\\scripts\\pip" install --upgrade pip'

    os.system(path)

    path = '"'+os.path.dirname(sys.executable)+'\\scripts\\pip" install unrar'

    os.system(path)

    from unrar import rarfile

def decryptRarZipFile(filename):

    #根据文件扩展名,使用不同的库

    if filename.endswith('.zip'):

        fp = zipfile.ZipFile(filename)

    elif filename.endswith('.rar'):

        fp = rarfile.RarFile(filename)

    #解压缩的目标文件夹

    desPath = filename[:-4]

    if not os.path.exists(desPath):

        os.mkdir(desPath)

    #先尝试不用密码解压缩,如果成功则表示压缩文件没有密码

    try:

        fp.extractall(desPath)

        fp.close()

        print('No password')

        return

    #使用密码字典进行暴力破解

    except:

        try:

            fpPwd = open('pwddict.txt')

        except:

            print('No dict file pwddict.txt in current directory.')

            return

        for pwd in fpPwd:

            pwd = pwd.rstrip()

            try:

                if filename.endswith('.zip'):

                    for file in fp.namelist():

                        #对zip文件需要重新编码再解码,避免中文乱码

                        fp.extract(file, path=desPath, pwd=pwd.encode())

                        os.rename(desPath+'\\'+file, desPath+'\\'+file.encode('cp437').decode('gbk'))

                    print('Success! ====>'+pwd)

                    fp.close()

                    break

                elif filename.endswith('.rar'):

                    fp.extractall(path=desPath, pwd=pwd)

                    print('Success! ====>'+pwd)

                    fp.close()

                    break

            except:

                pass

        fpPwd.close()

if __name__ == '__main__':

    filename = sys.argv[1]

    if os.path.isfile(filename) and filename.endswith(('.zip', '.rar')):

        decryptRarZipFile(filename)

    else:

        print('Must be Rar or Zip file')

温馨提示:单击文章顶部作者名字旁边浅蓝色的“Python小屋”进入公众号,关注后可以查看更多内容!

欢迎转发给您的朋友,或许这正是Ta需要的知识!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dongfuguo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值