程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python algorithm encrypts Python and docker

編輯:Python

Catalog

Preface

One Basic configuration install

Two Basic grammar 2.1 encryption Python Script

2.2 Run the encryption script

2.3 Publish encryption script

3、 ... and 、pyarmor&docker

3.1 Dockerfile

3.2 requirements.txt

3.3 Encryption function lock_by_pyarmor.py

3.4 The main function myprocessor.py

3.5 Create a mirror and verify the effect

Preface

To avoid the risk of code leakage , We often need to encrypt the code ,PyArmor Is a for encryption and protection Python Tools for scripting . It protects... At runtime Python The binary code of the script is not leaked , After setting encryption Python The validity period of the source code , Tying Set the encrypted Python Source code to hard disk 、 Network card and other hardware devices .

One Basic configuration install

pip install pyarmor

Update to the latest version :

pip install --upgrade pyarmor

Two Basic grammar 2.1 encryption Python Script

a) Single package , Single level directory only

Use command obfuscate To encrypt python Script . In the simplest case , The most common case is to switch to the main function script algorithm.py Path , And then execute :

pyarmor obfuscate algorithm.py

PyArmor Will encrypt algorithm.py And all under the same directory *.py file :

Create an output subdirectory dist

Generate encrypted main script algorithm.py Save in the output directory dist

Encrypt all other files in the same directory *.py file , Save to output directory dist

Generate all auxiliary files required to run the encryption script , Save to output directory dist

b) If there are multiple algorithm packages 、 Multi level directory
By default , Only others in the same directory as the main script *.py Will be encrypted at the same time . If you want recursive encryption All under the subdirectory *.py file , Use the following command :

pyarmor obfuscate --recursive algorithm.py

Be careful : Encryption only .py file , If the algorithm needs to call .csv,.json file , Copy directly to dist Just put it in the package corresponding to the folder

2.2 Run the encryption script

There is no need to install... To run the encryption script pyarmo

cd dist
python algorithm.py

2.3 Publish encryption script

At this point, you can publish the encryption script , To publish an encryption script, you only need to put all of the output paths dist Just copy the file .

3、 ... and 、pyarmor&docker

because pyarmo Encrypted scripts are sensitive to the running environment , So we'd better package the whole algorithm into an image , Encrypt when the container is started , And delete all unencrypted files , leave dist file

notes : As mentioned above ,pyarmo Only right .py File encryption , about .csv,.json Files cannot be encrypted , Nature is generating dist There is no non in the bag .py Postfix file , So we need to .csv Wait for files to move in dist in , Otherwise run dist There will be an error in the algorithm in .

Because my local is windows System , So generate .dll Suffix file , Put... Directly dist Making an image will report an error , Because the operation of the container requires .so file , So consider runtime encryption in the container , Generate .so, Then automatically remove the unencrypted text key , Leave only dist And required non .py Suffix file , In fact, it can also be used linux The system directly runs locally to generate dist, But don't forget to be non .py The suffix files and folders are copied in .

The following will be myprocessor As an example , Tell the whole process :

It can be seen that , There are multiple algorithm packages calling each other , And there are more non - .py file

3.1 DockerfileFROM python:3.6 # Import python3.6 Based on the environment RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime\ && echo 'Asia/Shanghai'>/etc/timezone # Synchronization system time COPY ./ ./app/ # Copy all the files and folders in the algorithm to the image WORKDIR /app/ # Set the... In the image app Home folder RUN pip3 install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple # Install the package required by the algorithm in the image RUN pyarmor obfuscate --recursive myprocessor.py # Recursively encrypt all algorithms RUN ls # Show app All documents in CMD ["python3","/app/dist/myprocessor.py"] # function dist The encrypted main function in 3.2 requirements.txt# Here is the module on which my algorithm depends ,pyarmor==7.4.2 Be sure to add. , Others depend on adding according to their own algorithms pyarmor==7.4.2pandas == 1.1.5numpy == 1.19.5requests == 2.25.13.3 Encryption function lock_by_pyarmor.py# -*- coding: utf-8 -*- import shutilimport osclass File_lock(): def __init__(self): self.root_path = os.getcwd() # Current working path def remove_and_del_unsecret_dir_f(self): ''' Remove unencrypted py and pyc file , Copy non py,pyc File to dist''' for root, dir, files in os.walk(self.root_path): if "dist" not in root: for file in files: if os.path.splitext(file)[-1] in ['.py', '.pyc']: # Delete all unencrypted .py and .pyc file os.remove(os.path.join(root, file)) else: # Due to the py The file cannot be encrypted , Therefore, non py Move the file to a folder with the same name , If you cannot find a folder with the same name, create a folder with the same name if root == self.root_path: dist_same_die_path = os.path.join(self.root_path, 'dist') else: dist_same_die_path = os.path.join(self.root_path, 'dist', os.path.basename(root)) if not os.path.exists(dist_same_die_path): os.mkdir(dist_same_die_path) shutil.move(os.path.join(root, file), dist_same_die_path) temp_list = os.listdir() # remove dist All empty folders outside temp_list.remove('dist') for i in temp_list: os.rmdir(i) def lock_by_pyarmor(self): # print(" Current working path :",self.root_path) # print("os.listdir", os.listdir()) if (not os.path.exists(os.path.join(self.root_path, "dist"))): # if dist non-existent os.system("pyarmor obfuscate --recursive myprocessor.py") # encryption self.remove_and_del_unsecret_dir_f() else: # print(" Encrypted folder :",os.listdir()) self.remove_and_del_unsecret_dir_f() # print(" After removing unencrypted files :",os.listdir())3.4 The main function myprocessor.pyfrom lock_by_pyarmor import File_lockdef call(arg, model, *args, **kwargs): lockf = File_lock() lockf.lock_by_pyarmor() from deviation_algothrim.get_deviation import Deviation from loss_power.get_loss_power import GetPower passif __name__ == "__main__": print(call(arg=None, model=None))

Be careful : Import the required content from other packages , Need to put lockf.lock_by_pyarmor() after , Otherwise , It has not been fully built dist file , It may call and report an error .

3.5 Create a mirror and verify the effect

docker build _t imag1 . After the image is created ,app The internal directory is :

docker run -d imag1 /bin/bash -c "tail -f /dev/null"

docker ps # Find the running container id

docker exec -it 2293ee92f3ca /bin/bash # Into the container

python /app/dist/myprocessor.py # Execute encrypted file

You can see app There are only dist file .
Finally, you need to repackage the started container into an image , And release to the harbor On :docker commit 2293ee92f3ca7 new_image, Discard the original image . Because there are unencrypted files in the original image , And you can visit .
You can export the encrypted files in the container to the local D disc : docker cp bf5f2e815b64:/app D:/

ps: If there is a problem , perhaps lock_by_pyarmor.py There is a better way to implement , I hope it can be corrected .

This is about python Algorithm encryption pyarmor And docker This is the end of the article , More about python Algorithm encryption content please search the previous articles of the software development network or continue to browse the following related articles. I hope you can support the software development network in the future !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved