You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中调用7z结合密码字典暴力破解7z压缩包?

问题:用Python调用7z实现密码列表暴力破解压缩包

我拥有一个7z压缩包和一份密码列表,希望通过该密码列表暴力破解这个压缩包。当前使用环境为Windows 10、Python 3.11.1以及7z 22.1.0.0,已编写如下Python代码:

path_7z: str = "C:/Program Files/7-Zip/7z.exe"
with open("passwords.txt", "r", encoding="UTF-8") as file:
    for pw in file:
        pw = pw.rstrip("/n")
        #call 7z with parameter {filepath} and {pw}, unpack archive if {pw} is correct, otherwise continue with the next {pw}

请问如何实现代码中最后一行注释的功能?


实现方案

核心思路是用Python的subprocess模块调用7z命令行工具,通过命令返回码判断密码是否正确。以下是完整实现代码:

import subprocess

path_7z: str = "C:/Program Files/7-Zip/7z.exe"
archive_path: str = "C:/path/to/your/archive.7z"  # 替换为你的7z压缩包路径
output_dir: str = "C:/path/to/output/folder"  # 替换为解压输出目录

with open("passwords.txt", "r", encoding="UTF-8") as file:
    for pw in file:
        pw = pw.rstrip("\n")  # 修正原代码的换行符错误,Python中换行符是\
        if not pw:
            continue  # 跳过空密码行
        
        # 用7z的t命令测试密码(比直接解压高效,仅验证密码有效性)
        # 若要直接解压,把"t"换成"x"即可
        command = [
            path_7z,
            "t",
            archive_path,
            f"-p{pw}",
            f"-o{output_dir}",
            "-y"  # 自动确认所有操作提示,避免程序卡住
        ]
        
        try:
            result = subprocess.run(
                command,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                check=False
            )
            
            # 7z验证成功返回码为0,失败返回非0值(通常为2)
            if result.returncode == 0:
                print(f"正确密码找到: {pw}")
                break  # 找到密码后终止循环
            else:
                print(f"密码无效: {pw}")
                
        except Exception as e:
            print(f"尝试密码 {pw} 时出错: {str(e)}")

关键细节说明

  • 命令选择:t命令仅验证密码和压缩包完整性,不实际解压,速度更快;如果需要直接解压,替换为x命令即可。
  • 参数注意:-p和密码、-o和输出目录之间不能有空格,这是7z命令行的语法要求。
  • 换行符修正:原代码中的rstrip("/n")是错误写法,Python和Windows下的换行符是\n,必须修正。
  • 异常处理:捕获命令执行时的异常,避免单个密码出错导致整个程序中断。

内容的提问来源于stack exchange,提问作者Vega

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:40:46