Python code security execution system and method based on sandbox environment

By using dynamic detection and resource isolation technology in a sandbox environment, dangerous modules in Python code can be identified and isolated, and resource usage can be monitored in real time. This solves the security risks and resource exhaustion problems in Python code execution and provides an easy-to-use and efficient secure execution system.

CN121637482APending Publication Date: 2026-03-10国网天津市电力公司高压分公司 +2
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-11-04
Publication Date
2026-03-10

AI Technical Summary

Technical Problem

Existing technologies struggle to effectively address security risks during Python code execution, particularly the destructive behavior of malicious code and resource exhaustion issues. Furthermore, they lack lightweight and user-friendly code execution systems.

Method used

It employs dynamic detection and resource isolation technology based on a sandbox environment, identifies dangerous modules and functions through abstract syntax tree parsing, combines multi-threaded monitoring of memory and CPU usage, provides a graphical interface for real-time monitoring and control, and supports secure execution in both development mode and EXE mode.

Benefits of technology

It effectively blocks malicious code, prevents sensitive data leakage, reduces resource consumption by 60%, shortens startup time, lowers the technical threshold, and is suitable for multilingual and international application scenarios.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121637482A_ABST
    Figure CN121637482A_ABST
Patent Text Reader

Abstract

The invention relates to a Python code security execution system based on a sandbox environment. The Python code security execution system comprises a security detection module, a sandbox environment module and a graphical interface module. The invention further relates to a Python code security execution method based on the sandbox environment. The method comprises the steps that S1, the environment is deployed; s2, uploading and detecting codes; s3, executing and monitoring codes; and S4, result processing and cleaning. The process covers the full period of code processing: after a user uploads a code folder, a system automatically locates a main program file and starts security detection, and a risk report is generated; after the detection is passed, copying the code to a sandbox directory and starting execution, continuously monitoring resource consumption during the period, and triggering the process to stop when the time exceeds the limit; after execution is finished, the sandbox environment is automatically cleaned, and a result is returned; the system supports self-definition of a danger module / function list through a configuration file, and a user can adjust a resource threshold value and a safety rule according to requirements.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The application belongs to the technical field of computer software security, and particularly relates to a Python code safe execution system and method based on a sandbox environment. BACKGROUND

[0002] With the wide application of Python language in the fields of Web development, data analysis and automation script, users frequently face the demand of executing unknown source code. However, such operation has multiple security risks: firstly, malicious code may execute system commands through interfaces such as os.system or subprocess.Popen, or inject malicious logic by using eval and exec functions; secondly, the code may cause resource exhaustion through infinite loop, recursive call or large array operation; in addition, unauthorized file reading and writing or network request may cause sensitive data leakage.

[0003] The existing solutions have obvious limitations: static analysis tools (such as bandit) are difficult to cover the dynamic generated code behavior, virtual machine or container technology (such as Docker) is difficult to meet the lightweight demand due to large resource overhead, and the chroot mechanism based on permission control lacks fine-grained monitoring capability.

[0004] Therefore, there is an urgent need for a code execution system and method that takes into account security, lightweight and ease of use. SUMMARY

[0005] The application aims to overcome the shortcomings of the prior art and provide a Python code safe execution system and method based on a sandbox environment, which covers the whole cycle of code processing: after the user uploads the code folder, the system automatically locates the main program file and starts the security detection, and generates a risk report; after the detection, the code is copied to the sandbox directory and started for execution, during which the resource consumption is continuously monitored, and the process is terminated when the limit is exceeded; after the execution is completed, the sandbox environment is automatically cleaned up and the result is returned; the system supports customizing the dangerous module / function list through the configuration file, and the user can adjust the resource threshold and security rules according to the demand.

[0006] The application solves the technical problem by the following technical scheme: A Python code safe execution system based on a sandbox environment, which aims to build a three-layer protection system of dynamic detection, resource isolation and visual interaction, and comprises a security detection module, a sandbox environment module and a graphical interface module. The security detection module identifies dangerous modules, dangerous functions and sensitive instructions in strings in the code through abstract syntax tree (AST) parsing technology, and captures syntax errors and runtime exceptions. The sandbox environment module creates an isolated temporary file system directory, uses a multi-thread monitoring mechanism to track the memory occupation, CPU usage and execution time of the process in real time, and supports two execution modes: child process mode and current process mode. The graphical interface module integrates code uploading, execution control, risk report display and resource monitoring functions, and provides English-Chinese switching, Markdown document parsing and remote execution extension interfaces.

[0007] A Python code security execution method based on a sandbox environment, which executes the system, the method aims to realize the automatic isolation and running of Python programs through dynamic security detection method and sandbox isolation technology, the steps of the method are: S1, environment deployment: install dependent libraries, start the main program, load the graphical interface; create a main window, set the layout, initialize the key components of the security detector, sandbox manager and resource limiter, generate a'sandbox' folder under the project directory, set the isolation environment variable, and complete the creation of the sandbox environment; S2, code uploading and detection: users upload code through the graphical interface, the system records the folder path, analyzes the folder content, recursively scans the folder, collects all '.py' and '.md' files, and automatically identifies the main program file. First, use the abstract syntax tree (Abstract Syntax Tree, AST) to check dangerous modules, then perform dynamic string scanning, check code strings line by line, match dangerous operations and capture syntax errors and exceptions, and feed back the detection results to the user through the graphical interface; S3, code execution and monitoring: prepare the execution environment, clear the sandbox directory, copy the user code files into the sandbox, and select the mode according to the running environment: If it is a development mode, start a child process, and if it is an EXE mode, simulate a safe environment in the current process. Next, start the execution thread, redirect the output to the interface terminal in real time, start the resource monitoring thread, check the memory, CPU and running time. If the resource is found to be over limit, the process will be terminated immediately and the reason for termination will be recorded. For the user end, the system performs real-time interaction and updates the information whether the running state is normal, refreshes the resource label every second, and provides the user with the options of stopping execution and viewing the manual; S4, result processing and cleaning: return the execution result and keep the output log of the last execution, delete the temporary files, keep the directory structure for next use, and reset the sandbox manager state.

[0008] The positive effects that can be produced by the present application are: 1. The dual detection mechanism of AST static analysis and sandbox dynamic isolation effectively blocks the destruction of malicious code to the host system, the file access control strategy can prevent sensitive data leakage, and more than 98% of dangerous API calls can be identified through testing.

[0009] 2. Real-time monitoring technology ensures dynamic control of memory, CPU and execution time, and custom threshold function meets differentiated scenario requirements, with resource occupation reduced by more than 60% compared with container technology, and startup time shortened to milliseconds.

[0010] 3. The graphical interface integrates code uploading, execution control and risk prompt functions, and real-time resource usage curve and execution log are displayed, supporting online review of Markdown format usage documents, which significantly reduces the technical threshold.

[0011] 4. The system supports development environment debugging and exe packaging deployment, provides remote execution interface and multi-language interface switching function, and adapts to international application scenarios. BRIEF DESCRIPTION OF DRAWINGS

[0012] Figure 1 is a system block diagram of the present application; Figure 2 is a safety detection module flow chart of the present application; Figure 3 is a sandbox environment module flow chart of the present application; Figure 4 is a graphical interface module flow chart of the present application. DETAILED DESCRIPTION

[0013] The present application will be further described in detail below through specific embodiments, the following embodiments are only descriptive and not limiting, and the protection scope of the present application cannot be limited by this.

[0014] As shown in Figures 1-4 , a Python code safety execution system based on a sandbox environment, the innovation of which lies in: the system aims to build a three-layer protection system of dynamic detection, resource isolation and visual interaction, the system includes a safety detection module, a sandbox environment module and a graphical interface module; The safety detection module identifies dangerous modules, dangerous functions and sensitive instructions in strings in the code through abstract syntax tree (AST) parsing technology, and captures syntax errors and runtime exceptions; The sandbox environment module creates an isolated temporary file system directory, uses a multi-thread monitoring mechanism to track the memory occupation, CPU usage and execution time of the process in real time, and supports two execution modes of sub-process mode and current process mode; The graphical interface module integrates code uploading, execution control, risk report display and resource monitoring functions, and provides Chinese-English switching, Markdown document parsing and remote execution extension interface.

[0015] The Python code safe execution method based on a sandbox environment, the innovation lies in: the system is executed, the method aims to realize the automatic isolation operation of the Python program through the dynamic safety detection method and the sandbox isolation technology, the steps of the method are: S1, environment deployment: install dependent library, start main program, load graphical interface; create main window, set layout, initialize safety detector, sandbox manager, resource restrictor key components, generate'sandbox' folder under project directory, set isolation environment variable, complete the creation of sandbox environment; S2, code uploading and detection: the user uploads the code through the graphical interface, the system records the folder path, analyzes the folder content, recursively scans the folder, collects all '.py' and '.md' files, and automatically identifies the main program file, first uses the Abstract Syntax Tree (AST) of the main program file to check dangerous modules, then performs dynamic string scanning, checks the code string line by line, matches dangerous operations and captures syntax errors and exceptions, and feeds back the detection result to the user through the graphical interface; S3, code execution and monitoring: prepare the execution environment, empty the sandbox directory, copy the user code file into the sandbox, and select the mode according to the running environment: If it is a development mode, start a sub-process, and if it is an EXE mode, simulate a safe environment in the current process, then start an execution thread, redirect the output to the interface terminal in real time, start a resource monitoring thread, check the memory, CPU and running time; if the resource is found to be over limit, the process is terminated immediately and the reason for stopping is recorded; for the user end, the system carries out real-time interaction, updates the information whether the running state is normal, refreshes the resource label every second, and provides the user with the options of stopping execution and viewing manual; S4, result processing and cleaning: return the execution result and retain the output log of the last execution, delete temporary files, retain the directory structure for next use, and reset the sandbox manager state.

[0016] The flow of the present application covers the whole cycle of code processing: after the user uploads the code folder, the system automatically locates the main program file and starts safety detection, generates a risk report; after passing the detection, the code is copied to the sandbox directory and execution is started, during which the resource consumption is continuously monitored, and the process is terminated when the limit is exceeded; after the execution is completed, the sandbox environment is automatically cleaned and the result is returned; the system supports customizing the dangerous module / function list through the configuration file, and the user can adjust the resource threshold and safety rules according to the requirements.

[0017] The present application specifically implements the whole process of environment deployment, code execution, security detection and resource monitoring, and the specific steps are as follows: Step S1: Environment deployment stage. Install dependent libraries in Python 3.7+ environment, including 'PyQt5' (graphical interface), 'psutil' (resource monitoring), 'ast' (AST analysis) and'shutil' (file operation), create sandbox root directory through 'os.makedirs' and set permission mask (umask 077) to ensure isolation. After starting the main program, load the graphical interface and initialize the configuration parameters, including resource threshold (memory 512MB, CPU 80%, time 300 seconds), dangerous module list (such as 'os','subprocess') and dangerous function list (such as 'eval', 'exec').

[0018] Step S2: Code uploading and detection stage. The user selects the code folder through the interface, and the system calls 'os.walk' to traverse the directory structure and locate the main program file (such as'main.py'). The security detection module uses AST analysis technology to recursively traverse the code tree nodes, detects dangerous module import in 'Import' node (such as 'import os'), dangerous function call in 'Call' node (such as 'os.system("rm -rf / ")'), and scans sensitive instructions in strings through regular expressions (such as're.search(r"rm -rf", code)'). The detection results are displayed in risk level (high / medium / low), and the user can choose to terminate the operation or continue execution.

[0019] Step S3: Code execution and monitoring stage: After the user confirms the risk report, the system calls'shutil.copytree' to copy the code to the sandbox directory, and starts the code according to the execution mode (subprocess / current process). The monitoring thread collects process resource data every second through 'psutil.Process': memory usage is obtained through'memory_info().rss', CPU usage calls 'cpu_percent' interface, and execution time is calculated by timestamp difference. If any index is out of limit (such as memory exceeding 512MB), trigger 'terminate()' to forcibly end the process and record the log.

[0020] Step S4: Result processing and cleanup phase. After the code execution is finished, the system captures the standard output and error streams, and displays the execution result (success / timeout / exception) and resource consumption data (peak memory, CPU occupation curve) on the interface. The'shutil.rmtree' is called to clean up the sandbox directory, ensuring that the temporary files are completely deleted. For remote execution scenarios, the client submits the code to the server through the HTTP protocol, and the server returns the result after asynchronous execution, supporting multi-task queues and load balancing.

[0021] Although the embodiments of the present application and the drawings are disclosed for illustrative purposes, those skilled in the art can understand that various substitutions, changes and modifications are possible without departing from the spirit and scope of the present application and the appended claims, and therefore the scope of the present application is not limited to the disclosed content of the embodiments and the drawings.

Claims

1. A Python code security execution system based on a sandbox environment, characterized in that: The system aims to build a three-layer protection system of dynamic detection, resource isolation and visual interaction, which includes a security detection module, a sandbox environment module and a graphical interface module. The security detection module identifies dangerous modules, dangerous functions and sensitive instructions in strings in the code through Abstract Syntax Tree (AST) parsing technology, and captures syntax errors and runtime exceptions. The sandbox environment module creates an isolated temporary file system directory, uses a multi-thread monitoring mechanism to track the memory usage, CPU usage and execution time of the process in real time, and supports two execution modes: child process mode and current process mode. The graphical interface module integrates code uploading, execution control, risk report display and resource monitoring functions, and provides English-Chinese switching, Markdown document parsing and remote execution extension interface.

2. A Python code security execution method based on a sandbox environment, characterized in that: The system as claimed in claim 1, the method aims to realize the automatic isolation and running of Python programs through dynamic security detection method and sandbox isolation technology, the steps of the method are: S1, environment deployment: install dependent libraries, start the main program, load the graphical interface; create a main window, set the layout, initialize the key components of the security detector, sandbox manager and resource limiter, generate a'sandbox' folder under the project directory, set the isolation environment variable, and complete the creation of the sandbox environment; S2, code uploading and detection: the user uploads the code through the graphical interface, the system records the folder path, analyzes the folder content, recursively scans the folder, collects all '.py' and '.md' files, and automatically identifies the main program file. First, use the Abstract Syntax Tree (AST) of the main program file to check dangerous modules, then perform dynamic string scanning, check code strings line by line, match dangerous operations and capture syntax errors and exceptions, and feed back the detection results to the user through the graphical interface; S3, code execution and monitoring: prepare the execution environment, clear the sandbox directory, copy the user code files into the sandbox, and select the mode according to the running environment: If it is development mode, start a child process, and if it is EXE mode, simulate a safe environment in the current process. Next, start the execution thread, redirect the output to the interface terminal in real time, start the resource monitoring thread, and check the memory, CPU and running time; If the resources are found to be over-limit, the process will be terminated immediately and the reason for termination will be recorded; For the user end, the system performs real-time interaction, updates the information whether the running state is normal, refreshes the resource labels every second, and provides the user with the options of stopping execution and viewing the manual; S4, result processing and cleaning: return the execution result and keep the output log of the last execution, delete the temporary files, keep the directory structure for next use, and reset the sandbox manager state.