0
# Command Line Tools
1
2
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.
3
4
## Capabilities
5
6
### Main CLI Entry Points
7
8
Core command-line interfaces for different analysis tasks.
9
10
```python { .api }
11
def entry_point() -> int:
12
"""
13
Main CLI entry point for androguard command.
14
15
Returns:
16
Exit code (0 for success, non-zero for error)
17
"""
18
19
def androaxml_main(argv: list = None) -> int:
20
"""
21
AXML to XML conversion CLI.
22
23
Parameters:
24
- argv: Command line arguments (uses sys.argv if None)
25
26
Returns:
27
Exit code
28
"""
29
30
def androarsc_main(argv: list = None) -> int:
31
"""
32
ARSC resource extraction CLI.
33
34
Parameters:
35
- argv: Command line arguments
36
37
Returns:
38
Exit code
39
"""
40
41
def androlyze_main(argv: list = None) -> int:
42
"""
43
Interactive analysis session CLI.
44
45
Parameters:
46
- argv: Command line arguments
47
48
Returns:
49
Exit code
50
"""
51
52
def androsign_main(argv: list = None) -> int:
53
"""
54
APK signature verification CLI.
55
56
Parameters:
57
- argv: Command line arguments
58
59
Returns:
60
Exit code
61
"""
62
63
def androdis_main(argv: list = None) -> int:
64
"""
65
DEX disassembly CLI.
66
67
Parameters:
68
- argv: Command line arguments
69
70
Returns:
71
Exit code
72
"""
73
```
74
75
### Analysis and Processing Commands
76
77
High-level analysis commands for common tasks.
78
79
```python { .api }
80
def analyze(argv: list = None) -> int:
81
"""
82
Comprehensive APK analysis CLI.
83
84
Command: androguard analyze <apk_file> [options]
85
86
Options:
87
- --output, -o: Output directory for results
88
- --format: Output format (text, json, xml)
89
- --verbose, -v: Verbose output
90
- --decompile: Include decompiled source
91
- --resources: Extract resources
92
93
Parameters:
94
- argv: Command line arguments
95
96
Returns:
97
Exit code
98
"""
99
100
def decompile(argv: list = None) -> int:
101
"""
102
APK/DEX decompilation CLI.
103
104
Command: androguard decompile <input_file> [options]
105
106
Options:
107
- --output, -o: Output directory
108
- --limit: Limit decompiled classes
109
- --jar: Also generate JAR files
110
- --pretty: Pretty print output
111
112
Parameters:
113
- argv: Command line arguments
114
115
Returns:
116
Exit code
117
"""
118
119
def disassemble(argv: list = None) -> int:
120
"""
121
DEX disassembly CLI.
122
123
Command: androguard disassemble <dex_file> [options]
124
125
Options:
126
- --output, -o: Output file
127
- --method: Specific method to disassemble
128
- --class: Specific class to disassemble
129
- --format: Output format
130
131
Parameters:
132
- argv: Command line arguments
133
134
Returns:
135
Exit code
136
"""
137
```
138
139
### File Processing Commands
140
141
Commands for processing specific file types and formats.
142
143
```python { .api }
144
def axml(argv: list = None) -> int:
145
"""
146
AXML file processing CLI.
147
148
Command: androguard axml <axml_file> [options]
149
150
Options:
151
- --output, -o: Output XML file
152
- --raw: Output raw XML without formatting
153
- --recursive: Process AXML files recursively
154
155
Parameters:
156
- argv: Command line arguments
157
158
Returns:
159
Exit code
160
"""
161
162
def arsc(argv: list = None) -> int:
163
"""
164
ARSC resource processing CLI.
165
166
Command: androguard arsc <arsc_file> [options]
167
168
Options:
169
- --output, -o: Output directory
170
- --package: Filter by package name
171
- --type: Filter by resource type
172
- --locale: Filter by locale
173
- --list: List available resources
174
175
Parameters:
176
- argv: Command line arguments
177
178
Returns:
179
Exit code
180
"""
181
182
def sign(argv: list = None) -> int:
183
"""
184
APK signature verification CLI.
185
186
Command: androguard sign <apk_file> [options]
187
188
Options:
189
- --certificate: Show certificate details
190
- --hash: Show certificate hashes
191
- --verify: Verify signature integrity
192
- --all: Show all signature versions
193
194
Parameters:
195
- argv: Command line arguments
196
197
Returns:
198
Exit code
199
"""
200
```
201
202
### Advanced Analysis Commands
203
204
Specialized commands for advanced analysis tasks.
205
206
```python { .api }
207
def cg(argv: list = None) -> int:
208
"""
209
Call graph generation CLI.
210
211
Command: androguard cg <input_file> [options]
212
213
Options:
214
- --output, -o: Output file (PNG, SVG, DOT)
215
- --format: Graph format
216
- --method: Filter methods
217
- --class: Filter classes
218
- --show-external: Include external calls
219
- --entry-points: Specify entry points
220
221
Parameters:
222
- argv: Command line arguments
223
224
Returns:
225
Exit code
226
"""
227
228
def trace(argv: list = None) -> int:
229
"""
230
Dynamic tracing CLI with Frida integration.
231
232
Command: androguard trace <package_name> [options]
233
234
Options:
235
- --device, -d: Target device
236
- --script, -s: Frida script file
237
- --methods: Methods to trace
238
- --classes: Classes to trace
239
- --output, -o: Output trace file
240
241
Parameters:
242
- argv: Command line arguments
243
244
Returns:
245
Exit code
246
"""
247
248
def dtrace(argv: list = None) -> int:
249
"""
250
Direct trace CLI for immediate tracing.
251
252
Command: androguard dtrace <target> [options]
253
254
Parameters:
255
- argv: Command line arguments
256
257
Returns:
258
Exit code
259
"""
260
261
def dump(argv: list = None) -> int:
262
"""
263
Memory dump CLI for runtime analysis.
264
265
Command: androguard dump <package_name> [options]
266
267
Options:
268
- --device, -d: Target device
269
- --output, -o: Output directory
270
- --dex: Dump DEX files
271
- --so: Dump shared libraries
272
- --data: Dump app data
273
274
Parameters:
275
- argv: Command line arguments
276
277
Returns:
278
Exit code
279
"""
280
```
281
282
### Utility Commands
283
284
Utility commands for identification and batch processing.
285
286
```python { .api }
287
def apkid(argv: list = None) -> int:
288
"""
289
APK identification CLI.
290
291
Command: androguard apkid <apk_file> [options]
292
293
Options:
294
- --json: Output as JSON
295
- --scan-dir: Scan directory recursively
296
- --timeout: Analysis timeout
297
298
Parameters:
299
- argv: Command line arguments
300
301
Returns:
302
Exit code
303
"""
304
305
def batch_process(argv: list = None) -> int:
306
"""
307
Batch processing CLI for multiple files.
308
309
Command: androguard batch <input_dir> [options]
310
311
Options:
312
- --output, -o: Output directory
313
- --workers: Number of parallel workers
314
- --format: Output format
315
- --filter: File filter pattern
316
317
Parameters:
318
- argv: Command line arguments
319
320
Returns:
321
Exit code
322
"""
323
```
324
325
## CLI Argument Parsing
326
327
Common argument parsing patterns and utilities used across CLI tools.
328
329
```python { .api }
330
def create_parser(description: str) -> object:
331
"""
332
Create argument parser with common options.
333
334
Parameters:
335
- description: Parser description text
336
337
Returns:
338
ArgumentParser object with standard options
339
"""
340
341
def add_common_arguments(parser: object) -> None:
342
"""
343
Add common CLI arguments to parser.
344
345
Parameters:
346
- parser: ArgumentParser object to modify
347
"""
348
349
def parse_input_files(args: object) -> list[str]:
350
"""
351
Parse and validate input file arguments.
352
353
Parameters:
354
- args: Parsed arguments object
355
356
Returns:
357
List of valid input file paths
358
"""
359
360
def setup_logging(args: object) -> None:
361
"""
362
Setup logging based on CLI arguments.
363
364
Parameters:
365
- args: Parsed arguments with verbosity settings
366
"""
367
```
368
369
### Output Formatting
370
371
Standardized output formatting for CLI tools.
372
373
```python { .api }
374
def format_output(data: dict, format_type: str) -> str:
375
"""
376
Format analysis output for CLI display.
377
378
Parameters:
379
- data: Analysis results dictionary
380
- format_type: Output format ('text', 'json', 'xml')
381
382
Returns:
383
Formatted output string
384
"""
385
386
def print_results(results: dict, output_file: str = None) -> None:
387
"""
388
Print or save analysis results.
389
390
Parameters:
391
- results: Analysis results to output
392
- output_file: Optional output file path
393
"""
394
395
def create_report(analysis_data: dict, template: str = None) -> str:
396
"""
397
Create formatted analysis report.
398
399
Parameters:
400
- analysis_data: Comprehensive analysis results
401
- template: Optional report template
402
403
Returns:
404
Formatted report string
405
"""
406
```
407
408
## Usage Examples
409
410
### Basic CLI Usage
411
412
```bash
413
# Analyze APK file
414
androguard analyze app.apk --output analysis_results --format json --decompile
415
416
# Convert AXML to readable XML
417
androguard axml AndroidManifest.xml --output AndroidManifest_readable.xml
418
419
# Extract resources from ARSC
420
androguard arsc resources.arsc --output extracted_resources --list
421
422
# Verify APK signature
423
androguard sign app.apk --certificate --verify
424
425
# Decompile APK to Java source
426
androguard decompile app.apk --output decompiled_source --pretty
427
428
# Generate call graph
429
androguard cg app.apk --output call_graph.png --format png --show-external
430
```
431
432
### Advanced CLI Workflows
433
434
```bash
435
# Batch process directory of APKs
436
androguard batch /path/to/apk/directory --output batch_results --workers 4
437
438
# Disassemble specific method
439
androguard disassemble classes.dex --method "Lcom/example/MainActivity;->onCreate" --output method.smali
440
441
# Extract resources for specific locale
442
androguard arsc resources.arsc --locale fr --type string --output french_strings.xml
443
444
# Trace application with Frida
445
androguard trace com.example.app --script trace_crypto.js --output trace_results.json
446
447
# Dump runtime DEX files
448
androguard dump com.example.app --dex --output runtime_dump
449
```
450
451
### Scripted Analysis Examples
452
453
```python
454
import subprocess
455
import json
456
import os
457
458
def analyze_apk_with_cli(apk_path, output_dir):
459
"""Use CLI tools for APK analysis via subprocess."""
460
461
# Ensure output directory exists
462
os.makedirs(output_dir, exist_ok=True)
463
464
# Run analysis with JSON output
465
analysis_cmd = [
466
"androguard", "analyze", apk_path,
467
"--output", output_dir,
468
"--format", "json",
469
"--decompile"
470
]
471
472
try:
473
result = subprocess.run(analysis_cmd, capture_output=True, text=True)
474
if result.returncode == 0:
475
print(f"✓ Analysis completed: {output_dir}")
476
477
# Load and process JSON results
478
json_file = os.path.join(output_dir, "analysis.json")
479
if os.path.exists(json_file):
480
with open(json_file) as f:
481
analysis_data = json.load(f)
482
return analysis_data
483
else:
484
print(f"✗ Analysis failed: {result.stderr}")
485
return None
486
487
except Exception as e:
488
print(f"✗ Error running analysis: {e}")
489
return None
490
491
def batch_process_directory(input_dir, output_dir):
492
"""Batch process directory using CLI tools."""
493
494
# Find all APK files
495
apk_files = []
496
for root, dirs, files in os.walk(input_dir):
497
for file in files:
498
if file.endswith('.apk'):
499
apk_files.append(os.path.join(root, file))
500
501
print(f"Found {len(apk_files)} APK files")
502
503
# Process each APK
504
results = {}
505
for apk_file in apk_files:
506
apk_name = os.path.basename(apk_file)
507
apk_output_dir = os.path.join(output_dir, apk_name.replace('.apk', ''))
508
509
print(f"Processing {apk_name}...")
510
analysis_result = analyze_apk_with_cli(apk_file, apk_output_dir)
511
results[apk_name] = analysis_result
512
513
return results
514
515
# Example usage
516
input_directory = "/path/to/apk/collection"
517
output_directory = "/path/to/analysis/results"
518
519
batch_results = batch_process_directory(input_directory, output_directory)
520
521
# Process results
522
successful = sum(1 for result in batch_results.values() if result is not None)
523
total = len(batch_results)
524
print(f"Successfully analyzed {successful}/{total} APK files")
525
```
526
527
### Pipeline Integration
528
529
```python
530
def create_analysis_pipeline(apk_path):
531
"""Create comprehensive analysis pipeline using CLI tools."""
532
533
base_name = os.path.basename(apk_path).replace('.apk', '')
534
output_dir = f"analysis_{base_name}"
535
536
# Step 1: Basic analysis
537
print("Step 1: Basic analysis...")
538
subprocess.run([
539
"androguard", "analyze", apk_path,
540
"--output", output_dir,
541
"--format", "json"
542
])
543
544
# Step 2: Signature verification
545
print("Step 2: Signature verification...")
546
subprocess.run([
547
"androguard", "sign", apk_path,
548
"--certificate", "--verify"
549
])
550
551
# Step 3: Resource extraction
552
print("Step 3: Resource extraction...")
553
subprocess.run([
554
"androguard", "arsc", apk_path,
555
"--output", f"{output_dir}/resources",
556
"--list"
557
])
558
559
# Step 4: Decompilation
560
print("Step 4: Decompilation...")
561
subprocess.run([
562
"androguard", "decompile", apk_path,
563
"--output", f"{output_dir}/source",
564
"--pretty"
565
])
566
567
# Step 5: Call graph generation
568
print("Step 5: Call graph generation...")
569
subprocess.run([
570
"androguard", "cg", apk_path,
571
"--output", f"{output_dir}/call_graph.png",
572
"--format", "png"
573
])
574
575
print(f"Analysis complete: {output_dir}")
576
return output_dir
577
578
# Run pipeline
579
result_dir = create_analysis_pipeline("target_app.apk")
580
```
581
582
### Custom CLI Tool Integration
583
584
```python
585
def run_custom_analysis(apk_file, config):
586
"""Run custom analysis using multiple CLI tools."""
587
588
commands = []
589
590
# Build command list based on config
591
if config.get('basic_analysis', True):
592
commands.append([
593
"androguard", "analyze", apk_file,
594
"--output", config['output_dir'],
595
"--format", config.get('format', 'json')
596
])
597
598
if config.get('extract_resources', False):
599
commands.append([
600
"androguard", "arsc", apk_file,
601
"--output", f"{config['output_dir']}/resources"
602
])
603
604
if config.get('decompile', False):
605
commands.append([
606
"androguard", "decompile", apk_file,
607
"--output", f"{config['output_dir']}/decompiled"
608
])
609
610
if config.get('generate_graphs', False):
611
commands.append([
612
"androguard", "cg", apk_file,
613
"--output", f"{config['output_dir']}/graphs/call_graph.png"
614
])
615
616
# Execute commands
617
results = []
618
for cmd in commands:
619
try:
620
result = subprocess.run(cmd, capture_output=True, text=True)
621
results.append({
622
'command': ' '.join(cmd),
623
'success': result.returncode == 0,
624
'output': result.stdout,
625
'error': result.stderr
626
})
627
except Exception as e:
628
results.append({
629
'command': ' '.join(cmd),
630
'success': False,
631
'error': str(e)
632
})
633
634
return results
635
636
# Example configuration
637
analysis_config = {
638
'output_dir': 'custom_analysis',
639
'format': 'json',
640
'basic_analysis': True,
641
'extract_resources': True,
642
'decompile': True,
643
'generate_graphs': True
644
}
645
646
results = run_custom_analysis("app.apk", analysis_config)
647
648
# Print results summary
649
for result in results:
650
status = "✓" if result['success'] else "✗"
651
print(f"{status} {result['command']}")
652
if not result['success'] and 'error' in result:
653
print(f" Error: {result['error']}")
654
```
655
656
## Console Script Entry Points
657
658
When installed via pip, androguard provides these console commands:
659
660
```python { .api }
661
# Main command
662
androguard = "androguard.cli.main:entry_point"
663
664
# Specialized tools
665
androaxml = "androguard.cli.axml_main:main"
666
androarsc = "androguard.cli.arsc_main:main"
667
androsign = "androguard.cli.sign_main:main"
668
androlyze = "androguard.cli.analyze_main:main"
669
androdis = "androguard.cli.disassemble_main:main"
670
androtrace = "androguard.cli.trace_main:main"
671
androdump = "androguard.cli.dump_main:main"
672
androcg = "androguard.cli.cg_main:main"
673
```
674
675
## Utility Functions
676
677
```python { .api }
678
def validate_file_type(filename: str) -> str:
679
"""
680
Validate and detect file type for CLI processing.
681
682
Parameters:
683
- filename: Path to file to validate
684
685
Returns:
686
File type string ('APK', 'DEX', 'AXML', 'ARSC', etc.)
687
"""
688
689
def setup_output_directory(output_path: str, overwrite: bool = False) -> str:
690
"""
691
Setup output directory for CLI tools.
692
693
Parameters:
694
- output_path: Desired output path
695
- overwrite: Allow overwriting existing directory
696
697
Returns:
698
Validated output directory path
699
"""
700
701
def parse_method_signature(signature: str) -> dict:
702
"""
703
Parse method signature for CLI filtering.
704
705
Parameters:
706
- signature: Method signature string
707
708
Returns:
709
Dictionary with parsed components
710
"""
711
712
def format_cli_output(data, format_type: str, pretty: bool = True) -> str:
713
"""
714
Format data for CLI output in specified format.
715
716
Parameters:
717
- data: Data to format
718
- format_type: Output format ('text', 'json', 'xml', 'csv')
719
- pretty: Enable pretty formatting
720
721
Returns:
722
Formatted output string
723
"""
724
```