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 .
pip install pyarmor
Update to the latest version :
Two Basic grammar 2.1 encryption Python Scriptpip install --upgrade pyarmor
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
There is no need to install... To run the encryption script pyarmo
2.3 Publish encryption scriptcd dist
python algorithm.py
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 .
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 generatingdist
There is no non in the bag.py
Postfix file , So we need to.csv
Wait for files to move indist
in , Otherwise rundist
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 :
3.1 DockerfileIt can be seen that , There are multiple algorithm packages calling each other , And there are more non -
.py
file
FROM 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.1
3.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))
3.5 Create a mirror and verify the effectBe 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 .
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 !