+
74
-

如何在linux上创建一个沙箱隔离的目录让python使用?

如何在linux上创建一个沙箱隔离的目录让python使用?

python只能对这个目录进行读写操作,其他目录无法获取(除了python的库包可以读取)

网友回复

+
10
-

在Linux上创建一个沙箱隔离的Python环境有多种方法,我推荐以下几种方案,从简单到复杂:

方案1:使用Firejail(最简单推荐)

Firejail是一个轻量级的沙箱工具,使用命名空间和seccomp-bpf进行隔离。

安装Firejail

# Ubuntu/Debian
sudo apt install firejail

# CentOS/RHEL/Fedora
sudo yum install firejail
# 或
sudo dnf install firejail

创建沙箱目录并运行Python

# 创建隔离目录
mkdir ~/python_sandbox

# 运行Python,只允许访问指定目录
firejail --private=~/python_sandbox --allow-debuggers python3

# 或者更严格的限制(禁止网络、只读系统库)
firejail --private=~/python_sandbox \
         --read-only=/usr \
         --read-only=/lib \
         --read-only=/lib64 \
         --read-only=/etc \
         --net=none \
         python3

创建配置文件(可选)

创建 ~/.config/firejail/python-sandbox.profile:

# Python沙箱配置
include /etc/firejail/default.profile
include /etc/firejail/disable-interpreters.inc
include /etc/firejail/disable-programs.inc

# 只允许访问沙箱目录和必要的系统目录
private ~/python_sandbox
read-only /usr
read-only /lib
read-only /lib64
read-only /etc
net none

# 允许Python库访问
whitelist /usr/lib/python3.*
whitelist /usr/local/lib/python3.*

使用配置文件运行:

firejail --profile=python-sandbox.profile python3

方案2:使用Docker容器

创建Dockerfile

FROM python:3.9-slim

# 创建工作目录
WORKDIR /sandbox

# 复制需要的Python包(可选)
# COPY requirements.txt .
# RUN pip install -r requirements.txt

# 设置权限
RUN chown -R nobody:nogroup /sandbox
USER nobody

# 默认命令
CMD ["python3"]

构建和运行

# 构建镜像
docker build -t python-sandbox...

点击查看剩余70%

我知道答案,我要回答