Self decompressing and executing code in python

2019-09-10 17:24发布

问题:

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.