Obfuscate a Python script in Unicode escape sequences

大憨熊 提交于 2020-01-05 05:37:10

问题


I want to obfuscate a Python script by using Unicode escape sequences.

For example,

print("Hello World")

in Unicode escape sequences is:

\x70\x72\x69\x6e\x74\x28\x22\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x22\x29

From my command line, I can achieve this with:

$ python3 -c \x70\x72\x69\x6e\x74\x28\x22\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x22\x29
Hello World

I've create a file and put the "Hello World" Unicode escape sequence in it as the source code.

But when I run it, I get:

$ python3 sample.py
SyntaxError: unexpected character after line continuation character

How can I use Unicode escape sequences in my source code.


回答1:


You can use a PEP 263 header, which tells Python which encoding the source code is written in.

The format is:

# coding=<encoding name>

By using the unicode_escape codec (selected from https://docs.python.org/3/library/codecs.html), Python will unescape your strings first.

sample.py

# coding=unicode_escape
\x70\x72\x69\x6e\x74\x28\x22\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x22\x29

Result:

$ python3 sample.py
Hello World


来源:https://stackoverflow.com/questions/38030487/obfuscate-a-python-script-in-unicode-escape-sequences

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