You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中调用C文件,避免subprocess模块触发异常?

问题解决思路

你的核心问题是直接调用C源文件而非编译后的可执行程序,系统无法直接执行C源码,这才导致了两种错误:

  • FileNotFoundError:系统找不到可执行的script.c(它是文本源码,不是可执行文件)
  • Exec format error:即使给了完整路径,C源码的格式也不符合系统可执行文件标准(比如Linux的ELF、Windows的PE)

解决步骤

  1. 先编译C源文件为可执行程序
    使用GCC编译(Windows下可使用MinGW或MSVC):

    # Linux/macOS
    gcc script.c -o script
    # Windows(生成script.exe)
    gcc script.c -o script.exe
    

    如果你的C程序需要执行shellcode,还需关闭栈保护和开启可执行栈:

    gcc script.c -o script -fno-stack-protector -z execstack
    
  2. 修改Python脚本调用可执行程序
    不要把二进制shellcode作为命令行参数传递(容易被截断或解析错误),建议通过标准输入(stdin)传递:

    #!/usr/bin/env python
    import subprocess
    
    shellcode_file = "shellcode.bin"
    
    try:
        with open(shellcode_file, "rb") as f:
            shellcode = f.read()
        
        # 调用编译后的可执行文件,通过stdin传入shellcode
        # Windows下替换为"./script.exe"
        subprocess.run(["./script"], input=shellcode, check=True)
    except FileNotFoundError as e:
        print(f"{e} 未找到,请确认已编译C程序。")
    except subprocess.CalledProcessError as e:
        print(f"程序执行出错: {e}")
    
  3. 确保C程序能正确读取shellcode
    你的C程序需要从标准输入读取传入的shellcode,示例代码:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        unsigned char shellcode[1024];
        // 从stdin读取shellcode
        ssize_t bytes_read = fread(shellcode, 1, sizeof(shellcode), stdin);
        if (bytes_read <= 0) {
            perror("读取shellcode失败");
            return 1;
        }
        
        // 若要执行shellcode,可添加以下代码(注意系统权限和安全限制)
        // ((void(*)())shellcode)();
        
        printf("成功读取 %zd 字节的shellcode\n", bytes_read);
        return 0;
    }
    

内容的提问来源于stack exchange,提问作者KimetsuVentex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 04:45:36