Comprehensive Python toolkit for Android application reverse engineering and security analysis.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pre-built command-line utilities for common analysis tasks including APK inspection, DEX analysis, signature verification, and more. Androguard provides comprehensive CLI tools for batch processing and scripted analysis workflows.
Core command-line interfaces for different analysis tasks.
def entry_point() -> int:
"""
Main CLI entry point for androguard command.
Returns:
Exit code (0 for success, non-zero for error)
"""
def androaxml_main(argv: list = None) -> int:
"""
AXML to XML conversion CLI.
Parameters:
- argv: Command line arguments (uses sys.argv if None)
Returns:
Exit code
"""
def androarsc_main(argv: list = None) -> int:
"""
ARSC resource extraction CLI.
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def androlyze_main(argv: list = None) -> int:
"""
Interactive analysis session CLI.
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def androsign_main(argv: list = None) -> int:
"""
APK signature verification CLI.
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def androdis_main(argv: list = None) -> int:
"""
DEX disassembly CLI.
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""High-level analysis commands for common tasks.
def analyze(argv: list = None) -> int:
"""
Comprehensive APK analysis CLI.
Command: androguard analyze <apk_file> [options]
Options:
- --output, -o: Output directory for results
- --format: Output format (text, json, xml)
- --verbose, -v: Verbose output
- --decompile: Include decompiled source
- --resources: Extract resources
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def decompile(argv: list = None) -> int:
"""
APK/DEX decompilation CLI.
Command: androguard decompile <input_file> [options]
Options:
- --output, -o: Output directory
- --limit: Limit decompiled classes
- --jar: Also generate JAR files
- --pretty: Pretty print output
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def disassemble(argv: list = None) -> int:
"""
DEX disassembly CLI.
Command: androguard disassemble <dex_file> [options]
Options:
- --output, -o: Output file
- --method: Specific method to disassemble
- --class: Specific class to disassemble
- --format: Output format
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""Commands for processing specific file types and formats.
def axml(argv: list = None) -> int:
"""
AXML file processing CLI.
Command: androguard axml <axml_file> [options]
Options:
- --output, -o: Output XML file
- --raw: Output raw XML without formatting
- --recursive: Process AXML files recursively
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def arsc(argv: list = None) -> int:
"""
ARSC resource processing CLI.
Command: androguard arsc <arsc_file> [options]
Options:
- --output, -o: Output directory
- --package: Filter by package name
- --type: Filter by resource type
- --locale: Filter by locale
- --list: List available resources
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def sign(argv: list = None) -> int:
"""
APK signature verification CLI.
Command: androguard sign <apk_file> [options]
Options:
- --certificate: Show certificate details
- --hash: Show certificate hashes
- --verify: Verify signature integrity
- --all: Show all signature versions
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""Specialized commands for advanced analysis tasks.
def cg(argv: list = None) -> int:
"""
Call graph generation CLI.
Command: androguard cg <input_file> [options]
Options:
- --output, -o: Output file (PNG, SVG, DOT)
- --format: Graph format
- --method: Filter methods
- --class: Filter classes
- --show-external: Include external calls
- --entry-points: Specify entry points
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def trace(argv: list = None) -> int:
"""
Dynamic tracing CLI with Frida integration.
Command: androguard trace <package_name> [options]
Options:
- --device, -d: Target device
- --script, -s: Frida script file
- --methods: Methods to trace
- --classes: Classes to trace
- --output, -o: Output trace file
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def dtrace(argv: list = None) -> int:
"""
Direct trace CLI for immediate tracing.
Command: androguard dtrace <target> [options]
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def dump(argv: list = None) -> int:
"""
Memory dump CLI for runtime analysis.
Command: androguard dump <package_name> [options]
Options:
- --device, -d: Target device
- --output, -o: Output directory
- --dex: Dump DEX files
- --so: Dump shared libraries
- --data: Dump app data
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""Utility commands for identification and batch processing.
def apkid(argv: list = None) -> int:
"""
APK identification CLI.
Command: androguard apkid <apk_file> [options]
Options:
- --json: Output as JSON
- --scan-dir: Scan directory recursively
- --timeout: Analysis timeout
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""
def batch_process(argv: list = None) -> int:
"""
Batch processing CLI for multiple files.
Command: androguard batch <input_dir> [options]
Options:
- --output, -o: Output directory
- --workers: Number of parallel workers
- --format: Output format
- --filter: File filter pattern
Parameters:
- argv: Command line arguments
Returns:
Exit code
"""Common argument parsing patterns and utilities used across CLI tools.
def create_parser(description: str) -> object:
"""
Create argument parser with common options.
Parameters:
- description: Parser description text
Returns:
ArgumentParser object with standard options
"""
def add_common_arguments(parser: object) -> None:
"""
Add common CLI arguments to parser.
Parameters:
- parser: ArgumentParser object to modify
"""
def parse_input_files(args: object) -> list[str]:
"""
Parse and validate input file arguments.
Parameters:
- args: Parsed arguments object
Returns:
List of valid input file paths
"""
def setup_logging(args: object) -> None:
"""
Setup logging based on CLI arguments.
Parameters:
- args: Parsed arguments with verbosity settings
"""Standardized output formatting for CLI tools.
def format_output(data: dict, format_type: str) -> str:
"""
Format analysis output for CLI display.
Parameters:
- data: Analysis results dictionary
- format_type: Output format ('text', 'json', 'xml')
Returns:
Formatted output string
"""
def print_results(results: dict, output_file: str = None) -> None:
"""
Print or save analysis results.
Parameters:
- results: Analysis results to output
- output_file: Optional output file path
"""
def create_report(analysis_data: dict, template: str = None) -> str:
"""
Create formatted analysis report.
Parameters:
- analysis_data: Comprehensive analysis results
- template: Optional report template
Returns:
Formatted report string
"""# Analyze APK file
androguard analyze app.apk --output analysis_results --format json --decompile
# Convert AXML to readable XML
androguard axml AndroidManifest.xml --output AndroidManifest_readable.xml
# Extract resources from ARSC
androguard arsc resources.arsc --output extracted_resources --list
# Verify APK signature
androguard sign app.apk --certificate --verify
# Decompile APK to Java source
androguard decompile app.apk --output decompiled_source --pretty
# Generate call graph
androguard cg app.apk --output call_graph.png --format png --show-external# Batch process directory of APKs
androguard batch /path/to/apk/directory --output batch_results --workers 4
# Disassemble specific method
androguard disassemble classes.dex --method "Lcom/example/MainActivity;->onCreate" --output method.smali
# Extract resources for specific locale
androguard arsc resources.arsc --locale fr --type string --output french_strings.xml
# Trace application with Frida
androguard trace com.example.app --script trace_crypto.js --output trace_results.json
# Dump runtime DEX files
androguard dump com.example.app --dex --output runtime_dumpimport subprocess
import json
import os
def analyze_apk_with_cli(apk_path, output_dir):
"""Use CLI tools for APK analysis via subprocess."""
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Run analysis with JSON output
analysis_cmd = [
"androguard", "analyze", apk_path,
"--output", output_dir,
"--format", "json",
"--decompile"
]
try:
result = subprocess.run(analysis_cmd, capture_output=True, text=True)
if result.returncode == 0:
print(f"✓ Analysis completed: {output_dir}")
# Load and process JSON results
json_file = os.path.join(output_dir, "analysis.json")
if os.path.exists(json_file):
with open(json_file) as f:
analysis_data = json.load(f)
return analysis_data
else:
print(f"✗ Analysis failed: {result.stderr}")
return None
except Exception as e:
print(f"✗ Error running analysis: {e}")
return None
def batch_process_directory(input_dir, output_dir):
"""Batch process directory using CLI tools."""
# Find all APK files
apk_files = []
for root, dirs, files in os.walk(input_dir):
for file in files:
if file.endswith('.apk'):
apk_files.append(os.path.join(root, file))
print(f"Found {len(apk_files)} APK files")
# Process each APK
results = {}
for apk_file in apk_files:
apk_name = os.path.basename(apk_file)
apk_output_dir = os.path.join(output_dir, apk_name.replace('.apk', ''))
print(f"Processing {apk_name}...")
analysis_result = analyze_apk_with_cli(apk_file, apk_output_dir)
results[apk_name] = analysis_result
return results
# Example usage
input_directory = "/path/to/apk/collection"
output_directory = "/path/to/analysis/results"
batch_results = batch_process_directory(input_directory, output_directory)
# Process results
successful = sum(1 for result in batch_results.values() if result is not None)
total = len(batch_results)
print(f"Successfully analyzed {successful}/{total} APK files")def create_analysis_pipeline(apk_path):
"""Create comprehensive analysis pipeline using CLI tools."""
base_name = os.path.basename(apk_path).replace('.apk', '')
output_dir = f"analysis_{base_name}"
# Step 1: Basic analysis
print("Step 1: Basic analysis...")
subprocess.run([
"androguard", "analyze", apk_path,
"--output", output_dir,
"--format", "json"
])
# Step 2: Signature verification
print("Step 2: Signature verification...")
subprocess.run([
"androguard", "sign", apk_path,
"--certificate", "--verify"
])
# Step 3: Resource extraction
print("Step 3: Resource extraction...")
subprocess.run([
"androguard", "arsc", apk_path,
"--output", f"{output_dir}/resources",
"--list"
])
# Step 4: Decompilation
print("Step 4: Decompilation...")
subprocess.run([
"androguard", "decompile", apk_path,
"--output", f"{output_dir}/source",
"--pretty"
])
# Step 5: Call graph generation
print("Step 5: Call graph generation...")
subprocess.run([
"androguard", "cg", apk_path,
"--output", f"{output_dir}/call_graph.png",
"--format", "png"
])
print(f"Analysis complete: {output_dir}")
return output_dir
# Run pipeline
result_dir = create_analysis_pipeline("target_app.apk")def run_custom_analysis(apk_file, config):
"""Run custom analysis using multiple CLI tools."""
commands = []
# Build command list based on config
if config.get('basic_analysis', True):
commands.append([
"androguard", "analyze", apk_file,
"--output", config['output_dir'],
"--format", config.get('format', 'json')
])
if config.get('extract_resources', False):
commands.append([
"androguard", "arsc", apk_file,
"--output", f"{config['output_dir']}/resources"
])
if config.get('decompile', False):
commands.append([
"androguard", "decompile", apk_file,
"--output", f"{config['output_dir']}/decompiled"
])
if config.get('generate_graphs', False):
commands.append([
"androguard", "cg", apk_file,
"--output", f"{config['output_dir']}/graphs/call_graph.png"
])
# Execute commands
results = []
for cmd in commands:
try:
result = subprocess.run(cmd, capture_output=True, text=True)
results.append({
'command': ' '.join(cmd),
'success': result.returncode == 0,
'output': result.stdout,
'error': result.stderr
})
except Exception as e:
results.append({
'command': ' '.join(cmd),
'success': False,
'error': str(e)
})
return results
# Example configuration
analysis_config = {
'output_dir': 'custom_analysis',
'format': 'json',
'basic_analysis': True,
'extract_resources': True,
'decompile': True,
'generate_graphs': True
}
results = run_custom_analysis("app.apk", analysis_config)
# Print results summary
for result in results:
status = "✓" if result['success'] else "✗"
print(f"{status} {result['command']}")
if not result['success'] and 'error' in result:
print(f" Error: {result['error']}")When installed via pip, androguard provides these console commands:
# Main command
androguard = "androguard.cli.main:entry_point"
# Specialized tools
androaxml = "androguard.cli.axml_main:main"
androarsc = "androguard.cli.arsc_main:main"
androsign = "androguard.cli.sign_main:main"
androlyze = "androguard.cli.analyze_main:main"
androdis = "androguard.cli.disassemble_main:main"
androtrace = "androguard.cli.trace_main:main"
androdump = "androguard.cli.dump_main:main"
androcg = "androguard.cli.cg_main:main"def validate_file_type(filename: str) -> str:
"""
Validate and detect file type for CLI processing.
Parameters:
- filename: Path to file to validate
Returns:
File type string ('APK', 'DEX', 'AXML', 'ARSC', etc.)
"""
def setup_output_directory(output_path: str, overwrite: bool = False) -> str:
"""
Setup output directory for CLI tools.
Parameters:
- output_path: Desired output path
- overwrite: Allow overwriting existing directory
Returns:
Validated output directory path
"""
def parse_method_signature(signature: str) -> dict:
"""
Parse method signature for CLI filtering.
Parameters:
- signature: Method signature string
Returns:
Dictionary with parsed components
"""
def format_cli_output(data, format_type: str, pretty: bool = True) -> str:
"""
Format data for CLI output in specified format.
Parameters:
- data: Data to format
- format_type: Output format ('text', 'json', 'xml', 'csv')
- pretty: Enable pretty formatting
Returns:
Formatted output string
"""Install with Tessl CLI
npx tessl i tessl/pypi-androguard