如何从函数创建pyc文件?

问题描述 投票:0回答:2

我正在用python编写的游戏中,并且我可以访问所有模块及其功能。

我不会获得一些较大函数的.pyc文件,因此我可以通过dePython或类似的东西来放置它。手动阅读这些功能会非常痛苦。

说我有Module.function,我该怎么做才能将该函数转换为.pyc文件?

谢谢!

python reverse-engineering bytecode pyc
2个回答
0
投票

您可以导入模块以自动生成.pyc,或者如果您希望以编程方式进行操作,请使用py_compile模块:http://docs.python.org/2/library/py_compile.html


0
投票

write_pycfile()中的xasm函数可以编写pycfile。它需要一个“ asm”对象,但基本上需要一个Python解释器版本和一个要编写的代码对象列表。它主要使用xdis中的功能。这是一个修改后的版本,主要显示了其工作原理:

import xdis
from xdis import PYTHON3
from xdis.magics import magics
from xdis.marsh import dumps
from struct import pack
import time


def write_pycfile(pyc_file, code_list, version=xdis.PYTHON_VERSION):
    if PYTHON3:
        file_mode = 'wb'
    else:
        file_mode = 'w'

    with open(pyc_file, file_mode) as fp:
        fp.write(magics[version])
        timestamp = int(time.time())
        fp.write(pack('I', timestamp))
        if version > 3.2:
            fp.write(pack('I', 0))
        for co in code_list:
            try:
                co_obj = dumps(co, python_version=str(version))
                if PYTHON3 and version < 3.0:
                    co_obj = str.encode(co_obj)
                    pass

                fp.write(co_obj)
            except:
                pass
            pass
    print("Wrote %s" % pyc_file)

write_pycfile("/tmp/test_pyc.pyc", [write_pycfile.__code__])

现在运行并分解:

$ python /tmp/write-pyc.py 
Wrote /tmp/test_pyc.pyc

$ pydisasm /tmp/test_pyc.pyc
# pydisasm version 4.3.2
# Python bytecode 3.6 (3379)
# Disassembled from Python 3.8.2 (default, Mar 28 2020, 12:46:55) 
# [GCC 7.5.0]
# Timestamp in code: 1587126086 (2020-04-17 08:21:26)
# Method Name:       write_pycfile
# Filename:          /tmp/write-pyc.py
# Argument count:    3
# Kw-only arguments: 0
# Number of locals:  8
# Stack size:        18
# Flags:             0x00000043 (NOFREE | NEWLOCALS | OPTIMIZED)
# First Line:        9
# Constants:
#    0: None
...
# Names:
....    
10:           0 LOAD_GLOBAL               0 (PYTHON3)
              2 POP_JUMP_IF_FALSE        10 (to 10)
...

使用uncompyle6最终反编译:

$ uncompyle6 /tmp/test_pyc.pyc
# uncompyle6 version 3.6.5
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.8.1 (default, Jan 23 2020, 17:02:14) 
# [GCC 7.4.0]
# Embedded file name: /tmp/write-pyc.py
# Compiled at: 2020-04-17 08:21:26
if PYTHON3:
    file_mode = 'wb'
else:
    file_mode = 'w'
with open(pyc_file, file_mode) as (fp):
    fp.write(magics[version])
    timestamp = int(time.time())
    fp.write(pack('I', timestamp))
    if version > 3.2:
        fp.write(pack('I', 0))
    for co in code_list:
        try:
            co_obj = dumps(co, python_version=(str(version)))
            if PYTHON3:
                if version < 3.0:
                    co_obj = str.encode(co_obj)
            fp.write(co_obj)
        except:
            pass

print('Wrote %s' % pyc_file)
# okay decompiling /tmp/test_pyc.pyc
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.