Self decompressing and executing code in python

扶醉桌前 提交于 2019-12-25 02:09:49

问题


This is the code that creates a compressed file with arbitrary python code in it. The idea is that you paste some kind of python program in the raw_code variable assignment, then run the script which creates a .py file which is functional python code that opens another python shell and executes the compressed code stored within it.

import zlib

raw_code = """print 'hello world' """

code_prefix = """import zlib
import os

compressed_code = \"\"\"
"""

code_postfix = """
\"\"\"

os.system('python ' + zlib.decompress(compressed_code))
"""

full_code = code_prefix + zlib.compress(raw_code) + code_postfix


with open("/some/kind/of/path/compCode.py", "wb") as outfile:
    outfile.write(full_code)

the file you get from this looks like this:

import zlib
import os

compressed_code = """
x��*(��+QP�H���W(�/�IQ�N�
"""

os.system('python ' + zlib.decompress(compressed_code))

The problem I'm running into is that trying to run the second file results in an error:

  File "compCode.py", line 6
SyntaxError: Non-ASCII character '\x9c' in file compressedPYCode.py on line 7, 
but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

adding an 'r' before the compressed_code variable doesn't help. Is what I'm trying to do actually possible?


回答1:


Try putting # -*- coding: utf-8 -*- on the first line of your script.

You may be able to force your encoding to get your string to load correctly but mileage may vary. If you have null bytes or something in the string they're obviously not going to be stored correctly.



来源:https://stackoverflow.com/questions/21153507/self-decompressing-and-executing-code-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!