Python shellexec 动态扩展模块

作者:hack1990 时间:12-09-17 阅读数:475人阅读

做测试用的,顺手写的一个python的c模块code,放在这里存放下做个sample。

这个模块主要是用c扩展了python,其中存在一个system方法,可以直接执行系统命令。类似于mysql的udf或者php的dl。这个在某些特定的python环境下可能形成突破(例如禁用了python自带的os.system)

找个目录,然后写两个文件:

system.c

#include <Python.h>
#include <string.h>

static PyObject * system_system(PyObject *self, PyObject *args) {

    const char *command;
    int sts;

    if (! PyArg_ParseTuple(args, "s", &command)) {
        return NULL;
    }

    sts = system(command);

    return Py_BuildValue("i", sts);
}

// Module's method table and initialization function
// See: http://docs.python.org/extending/extending.html#the-module-s-method-table-and-initialization-function
 static PyMethodDef SystemMethods[] = {
    {"system", system_system, METH_VARARGS, "Execute a shell command."},
    {NULL, NULL, 0, NULL}
};

void initsystem(void) {
    PyImport_AddModule("system");
    Py_InitModule("system", SystemMethods);
}

int main(int argc, char *argv[]) {
    Py_SetProgramName(argv[0]);
    Py_Initialize();
    initsystem();
    return 0;
}setup.py

from distutils.core import setup, Extension

ext = Extension('system', sources=['system.c'])

setup(name='system', version='1.0', description='Test description', ext_modules=[ext])然后在当前目录下执行:

python setup.py build这时候就会编译一个python的动态模块在build/lib.xxxxxxx/目录下。叫做system.so

然后你只要执行如下代码,即可成功调用:

Python 2.7.3 (default, Aug 30 2012, 23:03:58)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import imp
>>> imp.load_dynamic("system", "build/lib.linux-x86_64-2.7/system.so")
<module 'system' from 'build/lib.linux-x86_64-2.7/system.so'>
>>> import system
>>> system.system("whoami")
root
0

发表评论