用python批量解压带密码的压缩包

项目地址:

https://github.com/Mario-Hero/toolUnRar

环境需求

  • Windows系统
  • Python 3
  • 对于解压RAR文件,需要安装WinRAR
  • 对于解压7z/zip等其他7-Zip支持解压的文件,需要安装7-Zip

用法 Usage

直接拖入文件夹或压缩文件即可批量解压缩包含密码的压缩文件。如果拖入的是文件夹,则会把该文件夹下的压缩文件解压缩,但不进入下一级目录。通过设置PASSWD来设置字典,通过设置DELETEIT来设置解压后是否删除被成功解压的压缩文件。本脚本会通过文件的后缀识别该文件是否为压缩文件。

你可以把WinRAR目录下的Unrar.exe和7-Zip目录下的7z.exe直接复制到这个toolUnRar.py文件的相同目录下,这样就可以携带使用了。

参数 Parameters

  • PASSWD = ["hello","123456"] :你的密码本,该脚本会从这个数组中不断试验密码来解压缩,直到成功为止。
  • DELETEIT :一个危险的参数。为真时,该脚本会直接删除成功解压的压缩文件。为假则不会删除。
  • LOC_WINRAR = "C:\Program Files\WinRAR\" 你的WinRAR安装位置。就算这个变量的设置的不对,该程序也会在可能的位置来寻找对应的程序。
  • LOC_7Z:7-Zip的安装位置。
  • SAVE_MODE = True:如果该脚本无法通过后缀判断这是不是压缩文件,则不对该文件进行操作。

完整代码

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

# Created by Mario Chen, 04.04.2021, Shenzhen
# My Github site: https://github.com/Mario-Hero

import sys
import os
import subprocess

# you can change it >>>>>

PASSWD     = ["123456","hello"]  # the possible passwords
DELETEIT   = False                                     # DANGER!! If it is True,will delete rar file after extraction
LOC_WINRAR = "C:\\Program Files\\WinRAR\\"              # location of WinRAR
LOC_7Z     = "C:\\Program Files\\7-Zip\\"               # location of 7-Zip
SAVE_MODE  = True                                       # if the suffix of file doesn't look like a compressed file, then do nothing with it.

# <<<<< you can change it

PROGRAM_RAR  = "UnRAR.exe" # the program we use
PROGRAM_7Z   = "7z.exe"    # the program we use
LOC_S_WINRAR = ["C:\\Program Files\\WinRAR\\","C:\\Program Files (x86)\\WinRAR\\","./",""] # some possible locations of WinRAR
LOC_S_7Z     = ["C:\\Program Files\\7-Zip\\","C:\\Program Files (x86)\\7-Zip\\","./",""]   # some possible locations of 7-Zip
RAR_FILE     = ["rar","zip","7z","tar","gz","xz","bzip2","gzip","wim","arj","cab","chm","cpio","cramfs","deb","dmg","fat","hfs","iso","lzh","lzma","mbr","msi","nsis","ntfs","rpm","squashfs","udf","vhd","xar","z"]
NOT_RAR_FILE = ["jpg","exe","png","mkv","mp4","mp3","avi","mov","jpeg","wav","gif","mpeg","webp","txt","doc","docx","ppt","pptx","xls","xlsx","html","wps","torrent","swf","bmp","crdownload","xltd","downloading"]
ENABLE_RAR = False         # initial state only
ENABLE_7Z = False          # initial state only

# for guessing >>>
GUESS_FLAG_INIT     = ["密码", "码", "password", "Password"]    #0
GUESS_FLAG_START_1  = [":", ":"]                            #1
GUESS_FLAG_START_2  = ["是", "为", "is", "are"," "]          #1
GUESS_FLAG_END      = ["\n","   "]                           #2
GUESS_FLAG_DIVIDE   = ["或是", "或", " or "]                 #3
# <<< for guessing

def guessWDComment(comment):
    guess_flag = 0
    guess_wd: list[str] = []
    guess_ps = 0
    cutIn = 0
    cutOut = 0
    while True:
        if guess_flag == 0:
            guess_newPs = len(comment)
            guess_len = 0
            for initStr in GUESS_FLAG_INIT:
                ps_temp = comment.find(initStr, guess_ps)
                if ps_temp == -1:
                    continue
                else:
                    if ps_temp<guess_newPs:
                        guess_newPs = ps_temp
                        guess_len = len(initStr)
            if guess_newPs == len(comment):
                if not guess_wd:
                    cutIn = 0
                    cutOut = len(comment)
                    guess_flag = 3
                else:
                    break
            else:
                guess_ps = guess_newPs + guess_len
                guess_flag = 1
        elif guess_flag == 1:
            found_temp = False
            found_temp_2 = False
            guess_newPs = len(comment)
            for startStr in GUESS_FLAG_START_1:
                ps_temp = comment.find(startStr, guess_ps, guess_ps + 20)
                if ps_temp == -1:
                    continue
                else:
                    if ps_temp < guess_newPs:
                        found_temp = True
                        guess_newPs = ps_temp + len(startStr)
                        guess_flag = 2
            if found_temp:
                guess_ps = guess_newPs
                cutIn = guess_ps
                continue
            else:
                guess_newPs = len(comment)
                for startStr in GUESS_FLAG_START_2:
                    ps_temp = comment.find(startStr, guess_ps, guess_ps + 20)
                    if ps_temp == -1:
                        continue
                    else:
                        if ps_temp < guess_newPs:
                            found_temp_2 = True
                            guess_newPs = ps_temp + len(startStr)
                            guess_flag = 2
            if found_temp_2:
                guess_ps = guess_newPs
            cutIn = guess_ps
            guess_flag = 2
        elif guess_flag == 2:
            guess_newPs = len(comment)
            for endStr in GUESS_FLAG_END:
                ps_temp = comment.find(endStr, guess_ps)
                if ps_temp == -1:
                    continue
                else:
                    if ps_temp < guess_newPs:
                        guess_newPs = ps_temp
            guess_ps = guess_newPs
            guess_flag = 3
            cutOut = guess_ps
        elif guess_flag == 3:
            found_cut_temp = False
            for divideStr in GUESS_FLAG_DIVIDE:
                if comment.find(divideStr, cutIn, cutOut) != -1:
                    found_cut_temp = True
                    for wd in comment[cutIn:cutOut].split(divideStr):
                        guess_wd.append(wd.strip())
                    break
            if not found_cut_temp:
                guess_wd.append(comment[cutIn:cutOut].strip())
            guess_flag = 0
        else:
            guess_flag = 0
    return guess_wd

def isCompressedFile(file):
    file = file.lower()
    for rar in RAR_FILE:
        if file.endswith("." + rar):
            return True
    for media in NOT_RAR_FILE:
        if file.endswith("." + media):
            return False
    return not SAVE_MODE

def utfIsNumber(uchar):
    return uchar >= u'\u0030' and uchar<=u'\u0039'

def winRarDo(folder, file, wd):
    extractStr = " x -y -p" + wd + " \"" + folder + "\\" + file + "\" \"" + folder + "\\\""
    extM = subprocess.call("@\""+LOC_WINRAR+PROGRAM_RAR+"\""+extractStr,shell=True)
    if extM == 1:    # not rar file
        return 2
    elif extM == 11: # wrong password
        return 1
    elif extM != 0:  # error
        return 1
    else:
        return 0

def z7Do(folder, file, wd):
    extractStr = " x -y -p" + wd + " \"" + folder + "\\" + file + "\" -o\"" + folder + "\\\""
    extM = subprocess.call("@\""+LOC_7Z+PROGRAM_7Z+"\""+extractStr,shell=True)
    if extM !=0: # error
        return 1
    else:
        return 0

def unrarFile(folder, file):
    successThisFile = False
    fileNameEncrypted = True
    if not folder:
        cutPos = file.rindex("\\")
        folder = file[:cutPos]
        file = file[cutPos+1:]
        #print(folder)
        #print(file)
    if ENABLE_RAR and file.endswith(".rar"):
        winRarReturn = winRarDo(folder, file, PASSWD[0])
        #print(winRarReturn)
        if winRarReturn == 0:
            #successThisFile = True
            return True
        elif winRarReturn == 2:
            pass
        else:
            getCommentStr = " l -p0 -z" + " \"" + folder + "\\" + file + "\""
            commentNumber = subprocess.call("@\""+LOC_WINRAR+PROGRAM_RAR+"\""+getCommentStr,shell=True)
            #commentNumber = 1
            if commentNumber == 0:
                commentM = subprocess.getstatusoutput("@\""+LOC_WINRAR+PROGRAM_RAR+"\""+getCommentStr)
                if commentM[0] == 0:
                    fileNameEncrypted = False
                    comment = commentM[1][(commentM[1].index("\n\n")+2):commentM[1].index(folder)]
                    comment = comment[0:comment.rindex("\n\n")]
                    #print(comment)
                    if comment:
                        wdArray = guessWDComment(comment)
                        print("Possible passwords:", wdArray)
                        for wd in wdArray:
                            winRarReturn = winRarDo(folder, file, wd)
                            if winRarReturn == 1:
                                continue
                            elif winRarReturn == 0:
                                successThisFile = True
                                break
                            elif winRarReturn == 2:
                                break
                            else:
                                break
            if successThisFile:
                return True
            for index in range(1,len(PASSWD)):
                winRarReturn = winRarDo(folder, file, PASSWD[index])
                if winRarReturn == 1:
                    continue
                elif winRarReturn == 0:
                    successThisFile = True
                    PASSWD[0],PASSWD[index]=PASSWD[index],PASSWD[0]
                    break
                elif winRarReturn == 2:
                    break
                else:
                    break

    if not successThisFile:
        if ENABLE_7Z:
            for index in range(len(PASSWD)):
                z7Return = z7Do(folder, file, PASSWD[index])
                if z7Return == 1:
                    continue
                else:
                    successThisFile = True
                    PASSWD[0],PASSWD[index]=PASSWD[index],PASSWD[0]
                    break

    if not successThisFile:
        print("Failed:"+file)
    return successThisFile

def unrar(folder):
    if os.path.isdir(folder):
        print(folder)
        file_list = os.listdir(folder)
        for file in file_list:
            if os.path.isdir(folder + "/" + file):
                #print(folder +"/"+ file)
                #unrar(folder +"/"+file)
                pass
            else:
                if isCompressedFile(file):
                    if unrarFile(folder, file):
                        if DELETEIT:
                            os.remove(folder + "/" + file)
    else:
        if isCompressedFile(folder):
            if unrarFile("", folder):
                if DELETEIT:
                    os.remove(folder)

if __name__ == '__main__':
    if len(sys.argv) <= 1:
        sys.exit(1)
    testRar = os.popen("\""+LOC_WINRAR+PROGRAM_RAR+"\"").read()
    if not testRar:
       for loc in LOC_S_WINRAR:
           testRar = os.popen("\""+loc+PROGRAM_RAR+"\"").read()
           if testRar:
               LOC_WINRAR = loc
               ENABLE_RAR = True
               break
    else:
        ENABLE_RAR = True

    test7z = os.popen("\""+LOC_7Z+PROGRAM_7Z+"\"").read()
    if not test7z:
       for loc in LOC_S_7Z:
           test7z = os.popen("\""+loc+PROGRAM_7Z+"\"").read()
           if test7z:
               LOC_7Z = loc
               ENABLE_7Z = True
               break
    else:
        ENABLE_7Z = True

    if (not ENABLE_RAR) and (not ENABLE_7Z):
        print("Cannot find winRAR and 7-zip")
        sys.exit(1)
    while len(PASSWD) < 2:
        PASSWD.append("0")
    for folder in sys.argv[1:]:
        #print(folder)
        unrar(folder)
    print("Finish.")
    #subprocess.call("pause",shell=True)
    sys.exit(0)

以上就是用python批量解压带密码的压缩包的详细内容,更多关于python批量解压压缩包的资料请关注我们其它相关文章!

(0)

相关推荐

  • 使用 Python 破解压缩文件的密码的思路详解

    经常遇到百度网盘的压缩文件加密了,今天我们就破解它! 实现思路 上篇文章给大家介绍了爆破密码的思路,感兴趣的朋友可以了解下. 其实都大同小异:无非就是字典爆破,就看你是有现成密码字典,还是自己生成密码字典,然后进行循环输入密码,直到输入正确位置.现在很多都有防爆破限制,根本无法进行暴力破解,但是似乎zip这种大家都是用比较简单的密码而且没有什么限制. 因此 实现思路就是 生成字典->输入密码->成功解压 实现过程 1.  生成字典 生成密码字典其实就是一个字符组合的过程.小伙伴们可别用列表去组

  • Python解压 rar、zip、tar文件的方法

    Q1 :如何解压 rar 压缩包文件? A : Step1:检查是否有 rarfile 第三方库,若没有该模块,则需要进行安装 : Step2:参考代码如下: import rarfile import os rar=rarfile.RarFile(filename, mode='r') # mode的值只能为'r' # 判断同名文件夹是否存在,若不存在则创建同名文件夹 if os.path.isdir(os.path.splitext(filename)[0]): rf_list = rf.n

  • Python3压缩和解压缩实现代码

    一.说明 压缩和解压缩是日常常用的操作,不管是windows上图形界面的操作,还是linux上用命令来进行压缩解压缩,总的而言都还是比较方便的. 但用代码来实现就没做过,近期也得实现代码压缩与解压缩操作,所以就抽时间来研究一下. 二.zip文件压缩和解压缩实现 import os import zipfile # 函数功能是zip_file_list所有文件,和zip_dir_list所有目录下的所有文件,被压缩到一个zip_file_name的压缩文件中 def my_zip_function

  • Python实现加密的RAR文件解压的方法(密码已知)

    博主之前在网上找了很多资料,发现rarfile库不能直接调用,需要安装unrar模块,下面将详细介绍整个实现流程. 第一步:安装unrar模块,直接pip install unrar可能会找不到库,需要下载unrar library,也就是UnRAR.dll,下载地址为:http://www.rarlab.com/rar/UnRARDLL.exe: 第二步:将unrar安装路径添加到系统环境变量,64位操作系统的路径为C:\Program Files (x86)\UnrarDLL\x64,然后还

  • 文件上传服务器-jupyter 中python解压及压缩方式

    由于并不清楚服务器具体地址,只有jupyter 连接的情况下,上传文件. 方法一:用Linux命令 直接用linux命令,在jupyter中只需要在命令前加一个!即可.学校服务器上没有装zip,但装了tar,可以在压缩的时候选择文件压缩为.tar.gz的文件格式. 命令: !tar -zxvf ./Language-Detector.tar.gz 方法二: 用python的函数模块. ### 利用zipfile模块来压缩和解压文件 <br> 先将想要上传的多个文件压缩为.zip格式,在jupy

  • Python脚本破解压缩文件口令实例教程(zipfile)

    zipfile模块是python中一个处理压缩文件的模块,解决了不少我们平常需要处理压缩文件的需求 ,本文主要谈谈zipfile几个常用的用法. 环境:Windows python版本2.7.15 Python中操作zip压缩文件的模块是 zipfile . 相关文章:Python中zipfile压缩文件模块的使用 我们破解压缩文件的口令也是用的暴力破解方法.我们提前准备好密码字典用来爆破,如果密码字典中存在密码,则会打印出该密码,否则提示密码字典中无密码. main()函数用来打开密码字典 k

  • Python实现文件压缩和解压的示例代码

    大家可能都熟悉.zip格式的文件.它可以把多个文件,压缩成一个文件.这在网络上传输时很有用,而且节省硬盘空间. 接下来,我们使用Python实现压缩和解压. 读取ZIP文件信息 要读取ZIP文件的内容,首先必须创建一个ZipFile对象.ZipFile对象在概念上与File对象相似. 要创建一个 ZipFile 对象,就调用 zipfile.ZipFile()函数,向它传入一个字符串,表示.zip 文件的文件名. 请注意,zipfile 是 Python 模块的名称,ZipFile()是函数的名

  • python解压zip包中文乱码解决方法

    乱码得原因: 由于ZipFile模块导出遇到中文解码不对,windows上会出现,linux是否会出现不知道没测试过. 解决方式: 1. 搞个文件名引射表(不太方便,少量文件夹套用时候还可以) 2. 修改源码解码格式(不太方便,自己搞了一下,之后报其他错误) 3. 自己写入文件,自己创建文件夹(推荐) 自己创建的写法: with zipfile.ZipFile(file=zip_save_path, mode='r') as zf: # 解压到指定目录,首先创建一个解压目录 os.mkdir(u

  • Python在后台自动解压各种压缩文件的实现方法

    1.需求描述 编写一个 Python 程序,每次下载压缩包形式的文件后,自动将内部文件解压到当前文件夹后将压缩包删除,通过本案例可以学到的知识点: os 模块综合应用 glob 模块综合应用 利用 gzip zipfile rarfile tarfile 模块解压文件 2.步骤分析和前置知识 码代码之前需要将复杂问题解释成多个明确的要求,即这个程序实现的逻辑为: 定时检测某个文件夹(如 download 文件夹)是否存在压缩文件 如果有新出现的压缩文件则将其解压到当前文件夹内的新文件夹中 删除压

  • python 实现压缩和解压缩的示例

    一.说明 压缩和解压缩是日常常用的操作,不管是windows上图形界面的操作,还是linux上用命令来进行压缩解压缩,总的而言都还是比较方便的. 但用代码来实现就没做过,近期也得实现代码压缩与解压缩操作,所以就抽时间来研究一下. 二.zip文件压缩和解压缩实现 import os import zipfile # 函数功能是zip_file_list所有文件,和zip_dir_list所有目录下的所有文件,被压缩到一个zip_file_name的压缩文件中 def my_zip_function

  • python批量解压zip文件的方法

    这是一个用python写解压大量zip脚本的说明,本人新手一个,希望能对各位有所启发. 首先要注意的,在运行自己的脚本之前一定先备份或者复制出一些样本进行测试,不然出错会很麻烦: 之后我用到的是解压zip文件的扩展包zipfile,可以直接pip安装或者在IDE里安装,需要特别注意的是这个包的文件名解码方式需要我们去修改,先去查看源文件,直接搜索"cp437"(一个编码方式),找到后全部替换为"gbk",即可解决中文显示问题. 代码: import os impor

随机推荐