Python shellexec 动态扩展模块

admin 2021年4月3日19:31:16评论66 views字数 1603阅读5分20秒阅读模式

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

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

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

system.c

#include  
#include  

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")

>>> import system
>>> system.system("whoami")
root
0

转自:http://zone.wooyun.org/content/1019

文章来源于lcx.cc:Python shellexec 动态扩展模块

相关推荐: 维基泄密网站专泄国家机密 美政府无可奈何

  据新华网报道,近期,一个名叫Wikileaks(中文译名“维基泄密”)的网站名声大噪,初始原因是,今年4月初“维基泄密”披露了美国直升机滥杀伊拉克平民的视频。该视频共有800万人次的浏览量,让美军方十分被动。“维基泄密”网站专门致力于揭秘政府丑闻,平均每天…

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2021年4月3日19:31:16
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   Python shellexec 动态扩展模块http://cn-sec.com/archives/323124.html

发表评论

匿名网友 填写信息