1. 使用pyintaller打包代碼
pyinstaller abc.py # 要打包的top代碼
-F # 只生成單個的exe文件, 缺點是運行exe時要先解壓.
-w # 不生成命令行窗口.
--debug # 生成帶debug信息的exe文件.
--clean # 運行前清理編譯的臨時文件;
--icon # 工具的top圖標文件
--distpath # 輸出的exe存放的目錄
--workpath # 編譯的臨時文件存放的目錄
--hidden-import # 隱含import的模塊, 比如自定義/第三方的import模塊等
--key # 加密密鑰
2. pyc文件的破解
pyinstaller打包的py文件會轉為pyc格式, 但這種文件很容易破解出源碼.
操作如下:
- 下載pyinstxtractor.py;
- 從exe中獲取pyc文件: python pyinstxtractor.py ../dist/xx.exe;
- 在生成的xx.exe_extracted目錄中找到需要破解的pyc文件: yy.pyc;
- 使用在線反編譯工具https://tool.lu/pyc讀入pyc, 得到源碼.
3. 加密方法1: 將py文件轉為pyd格式
pyd是動態鏈接庫文件, 本質上與dll文件相同, 安全性比pyc文件高很多. 所以這種方式不算真正意義上的加密, 而是一個編譯過程.
操作如下:
- 安裝easycython模塊 pip install easycython
- 使用easycython命令將py轉pyd: easycython xx.py, 會在同一目錄生成xx.pyd(如果是64位系統生成的文件名為xx.cp36-win_amd64.pyd);
- 將xx.cp36-win_amd64.pyd重命名為xx.pyd;
- 使用pyinstaller打包(由於xx.py和xx.pyd在同一目錄, pyinstaller會優先打包pyd), 打包時添加—hidden-import xx選項.
- 生成的打包文件中會包含xx.pyd;
- 注意: 如果打包時使用了—key選項, 但打包的模塊是pyd格式的, 則pyd文件不會被加密, 只是打包.
4. 加密方法2: 使用pyinstaller的—key選項
操作如下:
- 安裝Visual Studio 2017 Community, 需要用到它的c語言編譯功能;
- 安裝PyCrypto模塊: pip install PyCrypto –i https://pypi.douban.com/simple, 需要調用該模塊;
- 運行pyinstaller --key 0123456789 –F [other options]
- 對生成的exe破解時, 會報告Fail to decompress xx, probably encrypted. 破解輸出的目錄中生成的是xx.pyc.encrypted文件, 不再是xx.pyc.
- 注意: 只能加密py文件, 如果加密的模塊是pyd文件, 則pyd文件會直接打包, 不會被加密.
- 聽說密鑰也一並打包到輸出文件中了, 所以好像也不安全. 感覺還是pyd靠譜些, 至少差不多是C編譯后的文件.
安裝或使用過程可能遇到的問題:
- 安裝PyCrypto模塊時, 報告錯誤:
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(27): error C2061: 語法錯誤: 標識符"intmax_t"
......
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(96): error C2143: 語法錯誤: 缺少"{"(在"__cdecl"的前面)
----------------------------------------
解決方法:
1) 將Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\stdint.h復制到C:\Program Files (x86)\Windows Kits\10\Include\10.0.17763.0\ucrt\stdint.h;
2) 將C:\Program Files (x86)\Windows Kits\10\Include\10.0.17763.0\ucrt\inttypes.h, 第14行, #include <stdint.h>修改為#include "stdint.h"
3) 重新安裝PyCrypto.
- pycryptodome模塊引起的問題. 網上有帖子說PyCrypto模塊已經停止維護, 推薦安裝pycryptodome模塊, 但這個模塊安裝后可能會引發一些錯誤.
1) 兩個模塊全都安裝, 加密/運行exe都沒問題;
2) 兩個模塊全都安裝, 然后卸載掉PyCrypto, 保留pycryptodome, 加密時報告: Crypto has not attribute '__version__';
3) 兩個模塊全都安裝, 然后卸載掉pycryptodome, 保留PyCrypto, 加密時報告: Crypto has not attribute '__version__';
4) 兩個模塊全都卸載, 然后單獨安裝pycryptodome, 加密成功, 但運行生成的exe, 但錯誤內容與第2)條又不相同:
1. $ ./hardware_debug_tool.exe
2. [27076] Failed to execute script pyiboot01_bootstrap
3. ......
4. zlib.error: Error -3 while decompressing data: incorrect header check
5.
6. During handling of the above exception, another exception occurred:
7.
8. Traceback (most recent call last):
9. ......
10. ImportError: Loader FrozenImporter cannot handle module os
解決方法:
- 只安裝PyCrypto模塊;
- 或者PyCrypto模塊和pycryptodome都安裝;
- 兩個模塊都安裝后, 想卸載某一個模塊時, 不能直接卸載其中一個, 只能兩個全部卸載, 然后重新安裝需要保留的模塊.
加密效果如這個網址上說的https://blog.csdn.net/mutex86/article/details/45367143: