idapython

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese


Python Execution SQL Functions

Python执行SQL函数

FunctionDescription
idapython_snippet(code[, sandbox])
Execute Python snippet and return captured output text
idapython_file(path[, sandbox])
Execute Python file and return captured output text
函数说明
idapython_snippet(code[, sandbox])
执行Python代码片段并返回捕获的输出文本
idapython_file(path[, sandbox])
执行Python文件并返回捕获的输出文本

Runtime Guard

运行时防护

Python execution is disabled by default. Enable it with:
sql
PRAGMA idasql.enable_idapython = 1;
Python执行默认处于禁用状态。可通过以下语句启用:
sql
PRAGMA idasql.enable_idapython = 1;

Examples

示例

sql
SELECT idapython_snippet('print("hello from idapython")');
SELECT idapython_file('C:/temp/script.py');
SELECT idapython_snippet('counter = globals().get("counter", 0) + 1; print(counter)', 'alpha');
sql
SELECT idapython_snippet('print("hello from idapython")');
SELECT idapython_file('C:/temp/script.py');
SELECT idapython_snippet('counter = globals().get("counter", 0) + 1; print(counter)', 'alpha');

Notes

注意事项

  • Disabled by default until pragma is enabled
  • Python exceptions propagate as SQL errors
  • sandbox
    isolates/persists Python globals by sandbox key
  • 默认禁用,需通过pragma启用
  • Python异常会作为SQL错误传播
  • sandbox
    参数可通过沙箱键隔离/持久化Python全局变量

Two Python Contexts (Important)

两种Python上下文(重要)

  • Host-side Python client (outside IDA): use
    requests.post(.../query, data=sql)
    to batch SQL over HTTP. Use this for loops, bulk updates, and automation orchestration. See
    connect
    skill HTTP client patterns.
  • IDAPython via SQL (inside IDA): use
    idapython_snippet()
    /
    idapython_file()
    when you need direct IDA SDK APIs in-process.
Example contrast:
python
undefined
  • 主机端Python客户端(IDA外部):使用
    requests.post(.../query, data=sql)
    通过HTTP批量发送SQL。适用于循环、批量更新和自动化编排。可参考
    connect
    技能的HTTP客户端模式。
  • 通过SQL调用的IDAPython(IDA内部):当需要在进程内直接访问IDA SDK API时,使用
    idapython_snippet()
    /
    idapython_file()
示例对比:
python
undefined

Host-side Python (outside IDA): sends SQL over HTTP

主机端Python(IDA外部):通过HTTP发送SQL

import requests requests.post("http://127.0.0.1:8081/query", data="SELECT COUNT(*) FROM funcs")

```sql
-- IDAPython (inside IDA): executes Python in IDA runtime
SELECT idapython_snippet('import idaapi; print(idaapi.get_kernel_version())');
import requests requests.post("http://127.0.0.1:8081/query", data="SELECT COUNT(*) FROM funcs")

```sql
-- IDAPython(IDA内部):在IDA运行时执行Python代码
SELECT idapython_snippet('import idaapi; print(idaapi.get_kernel_version())');

Sandbox Behavior

沙箱行为

Each sandbox key creates an isolated Python namespace:
  • Variables set in one sandbox are not visible in another
  • The same sandbox key reuses its namespace across calls (state persists within a session)
  • Without a sandbox key, code runs in the default global namespace
每个沙箱键都会创建一个独立的Python命名空间:
  • 在一个沙箱中设置的变量对其他沙箱不可见
  • 相同沙箱键会在多次调用中复用其命名空间(状态会在会话内持久化)
  • 若未指定沙箱键,代码会在默认全局命名空间中运行

Error Propagation

错误传播

When a Python script raises an exception, it propagates as a SQL error:
sql
-- This will return an error: "NameError: name 'undefined_var' is not defined"
SELECT idapython_snippet('print(undefined_var)');

当Python脚本抛出异常时,会作为SQL错误传播:
sql
-- 此语句会返回错误:"NameError: name 'undefined_var' is not defined"
SELECT idapython_snippet('print(undefined_var)');

When to Use IDAPython vs SQL

何时使用IDAPython vs SQL

Use CaseBest ToolWhy
Query/filter/aggregate dataSQLJOINs, CTEs, GROUP BY, window functions — SQL is purpose-built for this
Cross-table analysisSQLJOINing
funcs
,
xrefs
,
strings
,
ctree
is natural in SQL
Reporting and countingSQLCOUNT, SUM, AVG, GROUP_CONCAT — no Python loop needed
Complex algorithmsIDAPythonGraph algorithms, custom pattern matching, ML pipelines
IDA SDK APIs not in idasqlIDAPythonSome IDA SDK features aren't exposed as SQL tables/functions
UI automationIDAPythonOpening views, navigating cursor, triggering IDA actions
Existing scriptsIDAPythonReuse existing
.py
scripts without rewriting in SQL
General rule: Start with SQL. If you find yourself wanting nested loops, recursive algorithms, or IDA APIs that aren't exposed via idasql, reach for
idapython_snippet()
as a bridge.

使用场景最佳工具原因
查询/过滤/聚合数据SQLJOIN、CTE、GROUP BY、窗口函数——SQL专为这类操作设计
跨表分析SQL在SQL中关联
funcs
xrefs
strings
ctree
等表非常自然
报表与统计SQLCOUNT、SUM、AVG、GROUP_CONCAT——无需编写Python循环
复杂算法IDAPython图算法、自定义模式匹配、机器学习流水线
idasql未暴露的IDA SDK APIIDAPython部分IDA SDK功能未以SQL表/函数的形式暴露
UI自动化IDAPython打开视图、导航光标、触发IDA操作
现有脚本IDAPython无需重写即可复用现有的
.py
脚本
通用规则: 优先使用SQL。当你发现需要嵌套循环、递归算法,或者需要访问idasql未暴露的IDA API时,再使用
idapython_snippet()
作为桥梁。

Practical Use Cases

实际使用场景

Run a custom analysis script

运行自定义分析脚本

sql
-- Enable Python execution first
PRAGMA idasql.enable_idapython = 1;

-- Run a script that collects custom metrics
SELECT idapython_snippet('
import idautils, idc
count = 0
for func_ea in idautils.Functions():
    if idc.get_func_attr(func_ea, idc.FUNCATTR_FLAGS) & 0x4:  # FUNC_LIB
        count += 1
print(f"Library functions: {count}")
');
sql
-- 先启用Python执行
PRAGMA idasql.enable_idapython = 1;

-- 运行一个收集自定义指标的脚本
SELECT idapython_snippet('
import idautils, idc
count = 0
for func_ea in idautils.Functions():
    if idc.get_func_attr(func_ea, idc.FUNCATTR_FLAGS) & 0x4:  # FUNC_LIB
        count += 1
print(f"Library functions: {count}")
');

Access IDA SDK APIs not exposed through idasql

访问idasql未暴露的IDA SDK API

sql
-- Example: get processor-specific register names
SELECT idapython_snippet('
import ida_idp
for i in range(ida_idp.ph_get_regnames().__len__()):
    name = ida_idp.ph_get_regnames()[i]
    if name:
        print(f"{i}: {name}")
');
sql
-- 示例:获取处理器特定的寄存器名称
SELECT idapython_snippet('
import ida_idp
for i in range(ida_idp.ph_get_regnames().__len__()):
    name = ida_idp.ph_get_regnames()[i]
    if name:
        print(f"{i}: {name}")
');

Bridge pattern: Python produces JSON, SQL processes it

桥接模式:Python生成JSON,SQL处理数据

When you need Python's power for extraction but SQL's power for analysis:
sql
-- Python extracts data as JSON
SELECT idapython_snippet('
import json, idautils, idc
result = []
for ea in idautils.Functions():
    flags = idc.get_func_attr(ea, idc.FUNCATTR_FLAGS)
    if flags & 0x4:  # FUNC_LIB
        result.append({"ea": ea, "name": idc.get_func_name(ea)})
print(json.dumps(result))
');

-- Then process the JSON output in SQL using json_each()
-- (copy the output from above into the query)
当你需要用Python进行数据提取,同时用SQL进行数据分析时:
sql
-- Python将数据提取为JSON格式
SELECT idapython_snippet('
import json, idautils, idc
result = []
for ea in idautils.Functions():
    flags = idc.get_func_attr(ea, idc.FUNCATTR_FLAGS)
    if flags & 0x4:  # FUNC_LIB
        result.append({"ea": ea, "name": idc.get_func_name(ea)})
print(json.dumps(result))
');

-- 随后使用json_each()在SQL中处理JSON输出
-- (将上方的输出复制到查询中)