GKLBB

当你经历了暴风雨,你也就成为了暴风雨

导航

逆向分析 --- ghidra和ida导出所有函数名称脚本

IDA

1.保存下面脚本

import idautils
import idaapi
import idc

# 打开一个文件用于写入函数名称
with open("C:\\Users\\21558\\Downloads\\Compressed\\ghidra_11.1.1_PUBLIC_20240614\\ghidra_11.1.1_PUBLIC\\2.txt", "w") as file:
# 遍历所有函数
for function_ea in idautils.Functions():
function_name = idc.get_func_name(function_ea)
file.write(function_name + "\n")

print("Function names have been exported.")

 

2.打开ida,文件->脚本文件,运行

 

Ghidra

1.打开窗口-》脚本管理,右键新建,保存下面脚本,运行

# This script extracts all function names from the current Ghidra program
# and writes them to a specified output file. It is useful for documenting
# and analyzing the functions present in a binary or program being analyzed
# with Ghidra.

# Author: [Your Name]
# Category: _NEW_
# Keybinding: 
# Menupath: 
# Toolbar: 

# Import necessary Ghidra modules
from ghidra.program.model.listing import FunctionManager
from ghidra.util.task import TaskMonitor  # Correct import path for TaskMonitor

# Get the current program
program = getCurrentProgram()

# Get the function manager
function_manager = program.getFunctionManager()

# Get all functions in the current program
functions = function_manager.getFunctions(True)

# Open a file to write the function names
with open("C:\\Users\\21558\\Downloads\\Compressed\\ghidra_11.1.1_PUBLIC_20240614\\ghidra_11.1.1_PUBLIC\\1.txt", "wb") as file:
    # Iterate through all functions and write their names to the file
    for function in functions:
        try:
            file.write((function.getName() + "\n").encode('utf-8'))
        except UnicodeEncodeError as e:
            print("Encoding error for function {}: {}".format(function.getName(), e))

print("Function names have been exported.")

注意:修改你的文件输出路径

 

IDA Pro 导出所有函数名称脚本
根据您提供的脚本,我编写了一个简化版本,专门用于导出所有函数名称:

基础版本
Python

import idc
import idaapi
import idautils
import os
from datetime import datetime

def export_function_names(output_file="function_names.txt"):
    """
    导出所有函数名称到单个文件
    """
    print("开始导出函数名称...")
    
    # 获取所有函数
    functions = list(idautils.Functions())
    total_functions = len(functions)
    print(f"找到 {total_functions} 个函数")
    
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            # 写入头部信息
            f.write(f"# 函数名称导出\n")
            f.write(f"# 导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"# 函数总数: {total_functions}\n")
            f.write(f"# 格式: 地址 | 函数名称\n")
            f.write("=" * 60 + "\n\n")
            
            for func_ea in functions:
                func_name = idc.get_func_name(func_ea)
                f.write(f"0x{func_ea:08X} | {func_name}\n")
        
        print(f"导出完成! 文件保存在: {os.path.abspath(output_file)}")
        idc.msg(f"\n函数名称导出完成: {total_functions} 个函数 -> {output_file}\n")
        
    except Exception as e:
        print(f"导出失败: {e}")

# 执行导出
if __name__ == "__main__":
    export_function_names()
增强版本(包含更多信息)
Python

import idc
import idaapi
import idautils
import os
from datetime import datetime

def export_function_names_detailed(output_file="function_names_detailed.txt"):
    """
    导出所有函数名称(包含详细信息)
    """
    print("开始导出函数名称(详细版)...")
    
    functions = list(idautils.Functions())
    total_functions = len(functions)
    print(f"找到 {total_functions} 个函数")
    
    # 统计信息
    named_count = 0      # 有名称的函数
    sub_count = 0        # sub_开头的函数
    library_count = 0    # 库函数
    
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            # 写入头部信息
            f.write(f"{'='*70}\n")
            f.write(f"  函数名称导出报告\n")
            f.write(f"{'='*70}\n")
            f.write(f"导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"函数总数: {total_functions}\n")
            f.write(f"{'='*70}\n\n")
            
            # 写入表头
            f.write(f"{'地址':<14} | {'大小':<8} | {'类型':<8} | {'函数名称'}\n")
            f.write(f"{'-'*14}-+-{'-'*8}-+-{'-'*8}-+-{'-'*30}\n")
            
            for func_ea in functions:
                func_name = idc.get_func_name(func_ea)
                func = idaapi.get_func(func_ea)
                
                # 计算函数大小
                if func:
                    size = func.end_ea - func.start_ea
                else:
                    size = 0
                
                # 判断函数类型
                flags = idc.get_func_attr(func_ea, idc.FUNCATTR_FLAGS)
                if flags & idaapi.FUNC_LIB:
                    func_type = "库函数"
                    library_count += 1
                elif func_name.startswith("sub_"):
                    func_type = "未命名"
                    sub_count += 1
                else:
                    func_type = "已命名"
                    named_count += 1
                
                f.write(f"0x{func_ea:08X}   | {size:<8} | {func_type:<8} | {func_name}\n")
            
            # 写入统计信息
            f.write(f"\n{'='*70}\n")
            f.write(f"  统计信息\n")
            f.write(f"{'='*70}\n")
            f.write(f"已命名函数: {named_count}\n")
            f.write(f"未命名函数 (sub_): {sub_count}\n")
            f.write(f"库函数: {library_count}\n")
            f.write(f"总计: {total_functions}\n")
        
        print(f"导出完成!")
        print(f"  - 已命名: {named_count}")
        print(f"  - 未命名: {sub_count}")
        print(f"  - 库函数: {library_count}")
        print(f"文件: {os.path.abspath(output_file)}")
        
    except Exception as e:
        print(f"导出失败: {e}")

# 执行
if __name__ == "__main__":
    export_function_names_detailed()
多格式导出版本
Python

import idc
import idaapi
import idautils
import os
import json
import csv
from datetime import datetime

def export_all_formats(base_name="functions"):
    """
    导出函数名称为多种格式 (TXT, CSV, JSON)
    """
    print("开始多格式导出...")
    
    functions = list(idautils.Functions())
    total = len(functions)
    print(f"找到 {total} 个函数")
    
    # 收集函数数据
    func_data = []
    for func_ea in functions:
        func_name = idc.get_func_name(func_ea)
        func = idaapi.get_func(func_ea)
        size = (func.end_ea - func.start_ea) if func else 0
        
        func_data.append({
            "address": f"0x{func_ea:08X}",
            "address_dec": func_ea,
            "name": func_name,
            "size": size
        })
    
    # 1. 导出 TXT
    txt_file = f"{base_name}.txt"
    with open(txt_file, 'w', encoding='utf-8') as f:
        f.write(f"# 函数列表 ({total} 个)\n\n")
        for item in func_data:
            f.write(f"{item['address']} {item['name']}\n")
    print(f"✓ TXT: {txt_file}")
    
    # 2. 导出 CSV
    csv_file = f"{base_name}.csv"
    with open(csv_file, 'w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=["address", "name", "size"])
        writer.writeheader()
        writer.writerows(func_data)
    print(f"✓ CSV: {csv_file}")
    
    # 3. 导出 JSON
    json_file = f"{base_name}.json"
    with open(json_file, 'w', encoding='utf-8') as f:
        json.dump({
            "export_time": datetime.now().isoformat(),
            "total_functions": total,
            "functions": func_data
        }, f, indent=2, ensure_ascii=False)
    print(f"✓ JSON: {json_file}")
    
    # 4. 仅函数名列表
    names_file = f"{base_name}_names_only.txt"
    with open(names_file, 'w', encoding='utf-8') as f:
        for item in func_data:
            f.write(f"{item['name']}\n")
    print(f"✓ 纯名称: {names_file}")
    
    print(f"\n导出完成! 共 {total} 个函数")
    idc.msg(f"\n多格式导出完成: {total} 个函数\n")

# 执行
if __name__ == "__main__":
    export_all_formats()
输出示例
TXT 格式:

text

# 函数列表 (1234 个)

0x00401000 main
0x00401050 sub_401050
0x00401100 InitializeApp
...
CSV 格式:

csv

address,name,size
0x00401000,main,128
0x00401050,sub_401050,64
0x00401100,InitializeApp,256
JSON 格式:

JSON

{
  "export_time": "2024-01-15T10:30:00",
  "total_functions": 1234,
  "functions": [
    {"address": "0x00401000", "name": "main", "size": 128},
    ...
  ]
}
使用方法
text

在 IDA Pro 中:
1. File -> Script file...
2. 选择脚本文件
3. 或者在 Python 控制台中粘贴执行

 

posted on 2024-06-18 07:55  GKLBB  阅读(877)  评论(0)    收藏  举报