Introduction
Ghidra supports Python scripting through Jython, a Java implementation of Python 2.7. Python scripts provide a more concise syntax compared to Java while still offering full access to the Ghidra API.For modern Python 3 support, see PyGhidra which uses native CPython.
Python Script Structure
Basic Template
Script Metadata
Use comment directives for metadata:Accessing the Ghidra API
State Variables
Python scripts automatically have access to these variables:Importing Ghidra Classes
Common Operations
Address Manipulation
Memory Access
Listing Operations
Function Operations
Symbol Operations
Comments
Real Script Examples
Example 1: Locate Memory Address for File Offset
Source:LocateMemoryAddressesForFileOffset.py
Example 2: Find Strings in Called Functions
Source:RecursiveStringFinder.py (simplified)
User Interaction
Ask Methods
Output Methods
Python-Specific Features
List Comprehensions
Dictionary Usage
Exception Handling
Limitations
Jython 2.7
Jython is based on Python 2.7, which has several limitations:- No Python 3 syntax (print is a statement, not function)
- No f-strings
- Limited standard library
- No recent Python packages
Java Integration
Some Python idioms don’t work with Java objects:Performance
Jython scripts are generally slower than Java scripts due to interpretation overhead.Migrating to PyGhidra
For modern Python 3 support, consider PyGhidra:Best Practices
- Check for None - Always validate objects before use
- Use transactions - Wrap modifications in transactions
- Monitor cancellation - Check
monitor.isCancelled()in loops - Handle exceptions - Use try/except for robustness
- Import at top - Import all Ghidra classes at script start
