File size: 2,301 Bytes
6f5a20f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python3
"""
Simple Python wrapper for Apktool to decompile an Android APK file.
Usage: python decompile_apk.py <path_to_apk> [output_dir]
Requirements: Apktool must be installed and in PATH.
Best practices: Use argparse for CLI, handle errors, use pathlib for paths.
"""

import argparse
import os
import subprocess
import sys
from pathlib import Path


def check_apktool():
    """Check if Apktool is available in PATH."""
    try:
        subprocess.run(['apktool', '--version'], check=True, capture_output=True)
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False


def main():
    parser = argparse.ArgumentParser(description='Decompile an APK using Apktool.')
    parser.add_argument('apk_path', type=Path, help='Path to the APK file.')
    parser.add_argument('output_dir', type=Path, nargs='?', default=None,
                        help='Output directory (default: basename of APK without extension).')
    args = parser.parse_args()

    # Validate APK path
    if not args.apk_path.exists():
        print(f"Error: APK file '{args.apk_path}' not found.", file=sys.stderr)
        sys.exit(1)

    if not args.apk_path.suffix == '.apk':
        print("Error: Input file must be an APK.", file=sys.stderr)
        sys.exit(1)

    # Set output directory
    if args.output_dir is None:
        output_dir = args.apk_path.parent / args.apk_path.stem
    else:
        output_dir = args.output_dir

    # Check Apktool availability
    if not check_apktool():
        print("Error: Apktool is not installed or not in PATH.", file=sys.stderr)
        print("Install it from https://ibotpeaches.github.io/Apktool/", file=sys.stderr)
        sys.exit(1)

    print(f"Decompiling '{args.apk_path}' to '{output_dir}'...")

    # Create output directory
    output_dir.mkdir(parents=True, exist_ok=True)

    # Run Apktool decode
    try:
        subprocess.run(['apktool', 'd', str(args.apk_path), '-o', str(output_dir)],
                       check=True, capture_output=True)
        print(f"Decompilation complete. Output in: {output_dir}")
    except subprocess.CalledProcessError as e:
        print(f"Error during decompilation: {e.stderr.decode()}", file=sys.stderr)
        sys.exit(1)


if __name__ == '__main__':
    main()