Python调用7z批量解压带密码RAR及暴力破解密码

一颗松果
一颗松果
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍在Linux环境下使用Python调用系统7z命令批量解压RAR文件的方法。针对rarfile库支持不足的问题,通过apt安装7z-full及插件,重点强调-o和-p参数后不可加空格。代码展示了如何遍历目录解压,并支持传入密码列表进行暴力破解,将成功与失败文件分类存放。

Python调用7z批量解压RAR及暴力破解密码

起初尝试使用rarfile库处理压缩包,但该库对含密码的压缩包支持不佳,且在Linux系统中解压失败时不抛出异常。随后又尝试了unrar,发现操作比rarfile更为繁琐。

因此最终选择调用系统命令的方式,利用7z工具来完成解压任务。

可以通过apt包管理器安装7z-full以及7z的rar插件以支持相关格式。

需要注意一个关键细节:在命令行中,-o参数指定的输出目录和-p参数指定的密码,其后必须直接跟随内容,中间不能包含空格。

借助上述代码逻辑,还可以实现对压缩包密码的暴力破解功能。


# coding:utf-8 

import os

import zipfile

import traceback

import time

import shutil

import sys,getopt

 

succeedpath=""

unsucceedpath=""

psds={"2018","123456"}

 

 

opts,args=getopt.getopt(sys.argv[1:],"p:")

path=args[0]

for psd in args[1:]:

  psds.add(psd)

#for op,value in opts:

#  if op in ("-p","--password"):

#    psds.add(value)

 

 

def mkdirs(dirpath):

  global succeedpath,unsucceedpath

  succeedpath=os.path.join(dirpath,"0.succeed")

  unsucceedpath=os.path.join(dirpath,"0.unsucceed")

  if(not os.path.exists(succeedpath)):

    os.makedirs(succeedpath)

  if(not os.path.exists(unsucceedpath)):

    os.makedirs(unsucceedpath)

 

def extractdir(path):

  for filename in os.listdir(path):

    filepath=os.path.join(path,filename)

    if(os.path.isfile(filepath)):

      extractfile(filepath)

 

 

def extractfile(path):

  (dirpath,filen)=os.path.split(path)

  print("解压"+filen+"   ing...")

  try:

    if(filen.endswith(".rar") or filen.endswith(".zip")):

      path=os.path.abspath(path)

      dirpath=os.path.abspath(dirpath)

      cmd="7z x "+path+" -o"+dirpath+" -y "+" -p"

      state=False

      if(os.system(cmd)==0):

        state=True

      else:

        for psd in psds:

          cmdp="7z x "+path+" -p"+psd+" -y "+" -o"+dirpath

          if(os.system(cmdp)==0):

            state=True

            break

    else:

      return

    if (state):

      shutil.move(path,succeedpath)

    else:

      shutil.move(path,unsucceedpath)

      with open(os.path.join(dirpath,"errorinfo.txt"),"a+") as errorinfo:

        errorinfo.write("time:"+str(time.time())+"\n")

        errorinfo.write("解压出错!\n可能是密码错误!\n")

  except :

    with open(os.path.join(dirpath,"errorinfo.txt"),"a+") as errorinfo:

      errorinfo.write("time:"+str(time.time())+"\n")

      errorinfo.write("解压出错!\n")

      traceback.print_exc(file=errorinfo)

    shutil.move(path,unsucceedpath)

 
if(os.path.isdir(path)):

  dirpath=path

  mkdirs(dirpath)

  extractdir(dirpath)

elif(os.path.isfile(path)):

  filepath=path

  (dirpath,filename)=os.path.split(path)

  mkdirs(dirpath)

  extractfile(path)

else:

  print("输入错误!请重新输入!")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表