为啥使用虚拟环境

本地直接使用 pip install 提示错误信息,要在系统范围内安装包,建议使用 apt install python3-xyz 。系统范围的依赖不建议修改,各开发环境之间依赖还是隔离开比较好,各个环境可能需要不同版本的依赖包

$ pip install httpx
error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
    python3-xyz, where xyz is the package you are trying to
    install.
    
    If you wish to install a non-Debian-packaged Python package,
    create a virtual environment using python3 -m venv path/to/venv.
    Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
    sure you have python3-full installed.
    
    If you wish to install a non-Debian packaged Python application,
    it may be easiest to use pipx install xyz, which will manage a
    virtual environment for you. Make sure you have pipx installed.
    
    See /usr/share/doc/python3.12/README.venv for more information.

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.

环境准备

  1. 创建虚拟环境
$ python3 -m venv .dify-sandbox-python3
  1. 激活虚拟环境
$ source .dify-sandbox-python3/bin/activate
  1. 检查 python 命令
$ python
Python 3.12.3 (main, Mar  3 2026, 12:15:18) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
  1. 查看相关pip 配置
$ pip config list
global.index-url='https://mirrors.ustc.edu.cn/pypi/simple'
  1. 获取 python 默认加载模块路径
$ python
Python 3.12.3 (main, Mar  3 2026, 12:15:18) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.path)
['', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages']
>>> 

  1. 修改 dify-sandbox 的 conf/config.yaml
    将第5步获取的模块路径复制到 python_lib_path
app:
  port: 8194
  debug: True
  key: dify-sandbox
max_workers: 4
max_requests: 50
worker_timeout: 5
python_path: python
nodejs_path: /usr/local/node-v24.14.1/bin/node
python_lib_path:
  - "/usr/lib/python3.12"
  - "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages"
  - "/usr/lib/x86_64-linux-gnu"
  - "/etc/ssl/certs/ca-certificates.crt"
  - "/etc/nsswitch.conf"
  - "/etc/hosts"
  - "/etc/resolv.conf"
  - "/etc/localtime"
  - "/usr/share/zoneinfo"
  - "/etc/timezone"
enable_network: True # please make sure there is no network risk in your environment
enable_preload: False # please keep it as False for security purposes
log_path: "./logs" # path to store log files, default is "./logs"
allowed_syscalls: # please leave it empty if you have no idea how seccomp works
proxy:
  socks5: ''
  http: ''
  https: ''

启动服务,验证相关接口

  1. 清除sandbox-python相关的 lib 包,避免影响验证环境是否可行
# rm -rf /var/sandbox/sandbox-python/*
  1. 激活虚拟环境,启动服务
# source ../.dify-sandbox-python3/bin/activate
# ./main
{"time":"2026-04-16T22:19:35.068617743+08:00","level":"INFO","msg":"initializing nodejs runner environment"}
{"time":"2026-04-16T22:19:35.124300637+08:00","level":"INFO","msg":"nodejs runner environment initialized"}
{"time":"2026-04-16T22:19:35.125273122+08:00","level":"INFO","msg":"initializing python runner environment"}
{"time":"2026-04-16T22:19:35.126686582+08:00","level":"INFO","msg":"python runner environment initialized"}
{"time":"2026-04-16T22:19:35.127147413+08:00","level":"INFO","msg":"network has been enabled"}
{"time":"2026-04-16T22:19:35.127189865+08:00","level":"INFO","msg":"config init success"}
{"time":"2026-04-16T22:19:35.127256556+08:00","level":"INFO","msg":"runner dependencies init success"}
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:	export GIN_MODE=release
 - using code:	gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /health                   --> github.com/langgenius/dify-sandbox/internal/controller.Setup.func1 (5 handlers)
{"time":"2026-04-16T22:19:35.127331159+08:00","level":"INFO","msg":"setting max requests","max":50}
{"time":"2026-04-16T22:19:35.127349763+08:00","level":"INFO","msg":"setting max workers","max":4}
[GIN-debug] POST   /v1/sandbox/run           --> github.com/langgenius/dify-sandbox/internal/controller.RunSandboxController (9 handlers)
[GIN-debug] GET    /v1/sandbox/dependencies  --> github.com/langgenius/dify-sandbox/internal/controller.GetDependencies (6 handlers)
[GIN-debug] POST   /v1/sandbox/dependencies/update --> github.com/langgenius/dify-sandbox/internal/controller.UpdateDependencies (6 handlers)
[GIN-debug] GET    /v1/sandbox/dependencies/refresh --> github.com/langgenius/dify-sandbox/internal/controller.RefreshDependencies (6 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8194
{"time":"2026-04-16T22:19:35.127444004+08:00","level":"INFO","msg":"installing python dependencies"}
{"time":"2026-04-16T22:19:35.127526811+08:00","level":"INFO","msg":"python dependencies installed"}
{"time":"2026-04-16T22:19:35.127539828+08:00","level":"INFO","msg":"initializing python dependencies sandbox"}
  1. 运行测试接口
    test_dify_sandbox.sh 脚本内容
$ cat test_dify_sandbox.sh 
#!/bin/bash

REQUEST_HOST=http://localhost:8194
X_API_KEY=dify-sandbox

# 健康检查接口
echo "健康检查接口:/health"
curl ${REQUEST_HOST}/health

# Python3 示例
echo ""
echo "Python3 运行代码:/v1/sandbox/run"
curl -X POST ${REQUEST_HOST}/v1/sandbox/run \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: ${X_API_KEY}" \
  -d '{
    "language": "python3",
    "code": "import json\nperson = {\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}\njson_str = json.dumps(person)\nprint(json_str)",
    "preload": "",
    "enable_network": false
  }'

echo ""
echo "Node.js 运行代码:/v1/sandbox/run"
# Node.js 示例
curl -X POST ${REQUEST_HOST}/v1/sandbox/run \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: ${X_API_KEY}" \
  -d '{
    "language": "nodejs",
    "code": "const person = {name: \"John\", age: 30, city: \"New York\"};\nconst jsonString = JSON.stringify(person);\nconsole.log(jsonString);",
    "preload": "",
    "enable_network": false
  }'


echo ""
echo "更新依赖 复制python_lib_path依赖:/v1/sandbox/dependencies/update"
curl -X POST ${REQUEST_HOST}/v1/sandbox/dependencies/update \
     -H "Content-Type: application/json" \
     -H "X-Api-Key: ${X_API_KEY}" \
     -d '{"language": "python3"}'

echo ""
echo "刷新依赖dependencies/python-requirements.txt依赖:/v1/sandbox/dependencies/refresh"
curl -X GET ${REQUEST_HOST}/v1/sandbox/dependencies/refresh \
     -H "Content-Type: application/json" \
     -H "X-Api-Key: ${X_API_KEY}" \
     -d '{"language": "python3"}'


echo ""
echo "获取已安装依赖:/v1/sandbox/dependencies"
curl -X GET ${REQUEST_HOST}/v1/sandbox/dependencies \
     -H "Content-Type: application/json" \
     -H "X-Api-Key: ${X_API_KEY}" \
     -d '{"language": "python3"}'

echo ""

执行结果

$ sh test_dify_sandbox.sh 
健康检查接口:/health
"ok"
Python3 运行代码:/v1/sandbox/run
{"code":0,"message":"success","data":{"error":"","stdout":"{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}\n"}}
Node.js 运行代码:/v1/sandbox/run
{"code":0,"message":"success","data":{"error":"","stdout":"{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}\n"}}
更新依赖 复制python_lib_path依赖:/v1/sandbox/dependencies/update
{"code":0,"message":"success","data":{}}
刷新依赖dependencies/python-requirements.txt依赖:/v1/sandbox/dependencies/refresh
{"code":0,"message":"success","data":{"dependencies":[{"name":"jinja2","version":""},{"name":"httpx","version":""},{"name":"requests","version":""}]}}
获取已安装依赖:/v1/sandbox/dependencies
{"code":0,"message":"success","data":{"dependencies":[{"name":"jinja2","version":""},{"name":"httpx","version":""},{"name":"requests","version":""}]}}

虚拟环境中执行集成测试报错 ModuleNotFoundError 问题排查

执行集成测试

# go test -timeout 120s -v ./tests/integration_tests/...

报错信息如下

python_feature_test.go:79: unexpected error: ==================================================
        Code execution failed with exception:
        ==================================================
        Exception type: ModuleNotFoundError
        Exception message: No module named 'requests'
        --------------------------------------------------
        Traceback:
        Traceback (most recent call last):
          File "/var/sandbox/sandbox-python/tmp/3eaf988d_8d86_4047_8b36_b1f021567d87.py", line 53, in <module>
          File "<fd3>", line 4, in <module>
        ModuleNotFoundError: No module named 'requests'
        ==================================================
        exit code:42exit status 42error: exit status 42

首先检查当前虚拟环境中是否有 requests 包

(.dify-sandbox-python3) root@scd:/home/scd/code/go/dify/dify-sandbox# pip list
Package            Version
------------------ ---------
anyio              4.13.0
certifi            2026.2.25
charset-normalizer 3.4.7
h11                0.16.0
httpcore           1.0.9
httpx              0.28.1
idna               3.11
pillow             10.2.0
pip                24.0
requests           2.33.1
typing_extensions  4.15.0
urllib3            2.6.3

发现有 requests,难道是没有复制到 /var/sandbox/sandbox-python 里面,查看对应的 site-packages

$ ll /var/sandbox/sandbox-python/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages|grep requests
drwxr-xr-x  3 root root   4096 Apr 26 19:17 requests/
drwxr-xr-x  3 root root   4096 Apr 26 19:17 requests-2.33.1.dist-info/

增加 python_feature_test.go 的 测试方法,输出当前执行的时候默认加载模块的路径

func TestPythonPath(t *testing.T) {
	// Test case for http
	runMultipleTestings(t, 1, func(t *testing.T) {
		resp := service.RunPython3Code(context.TODO(), `
import sys
print(sys.path)
	`, "", &types.RunnerOptions{
			EnableNetwork: true,
		})
		t.Logf("TestPythons:%v\n", resp)
		if resp.Data.(*service.RunCodeResponse).Stdout != "" {
			t.Logf("TestPythons stdout: %s\n", resp.Data.(*service.RunCodeResponse).Stdout)
		}
		if resp.Code != 0 {
			t.Fatal(resp)
		}

		if resp.Data.(*service.RunCodeResponse).Stderr != "" {
			t.Fatalf("unexpected error: %s\n", resp.Data.(*service.RunCodeResponse).Stderr)
		}
	})
}

再次执行测试 go test -timeout 120s -v ./tests/integration_tests/...

=== RUN   TestPythonPath
    python_feature_test.go:68: TestPythons:&{0 success 0xc00038f2a0}
    python_feature_test.go:70: TestPythons stdout: ['/var/sandbox/sandbox-python/tmp', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/usr/local/lib/python3.12/dist-packages', '/usr/lib/python3/dist-packages']
        
--- PASS: TestPythonPath (0.05s)

这里的默认的导入路径和之前虚拟环境的不一样

(.dify-sandbox-python3) root@scd:/home/scd/code/go/dify/dify-sandbox# python
Python 3.12.3 (main, Mar 23 2026, 19:04:32) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.path)
['', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages']
>>> 

并没有对应的 /home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages 路径,获取的是系统python的默认路径

scd@scd:~$ python3
Python 3.12.3 (main, Mar 23 2026, 19:04:32) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.path)
['', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/usr/local/lib/python3.12/dist-packages', '/usr/lib/python3/dist-packages']

可以使用 .pth 文件‌,引用到对应的虚拟环境的路径 /home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages

在 Python 中,“.pth 文件”通常指代两种完全不同的概念:一种是用于‌扩展模块搜索路径的配置文件‌(纯文本),另一种是 PyTorch 中用于‌保存模型权重的二进制文件‌。请根据你的实际需求选择对应的编写方法。

编写 pth 文件‌ 引用虚拟路径

首先查看原来的 site-package 的路径

$ python3
Python 3.12.3 (main, Mar 23 2026, 19:04:32) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import site
>>> print(site.getsitepackages())
['/usr/local/lib/python3.12/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.12/dist-packages']
$ ll /usr/local/lib/python3.12/dist-packages
total 8
drwxr-xr-x 2 root root 4096 Apr 26 19:35 ./
drwxr-xr-x 3 root root 4096 Feb 15  2025 ../

在 /usr/local/lib/python3.12/dist-packages 路径下新增一个文件 dify_sandbox_python_venv.pth

# cat /usr/local/lib/python3.12/dist-packages/dify_sandbox_python_venv.pth 
/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages

检查系统的python的默认导入路径是否引用了这个路径

root@scd:/home/scd# python3
Python 3.12.3 (main, Mar 23 2026, 19:04:32) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.path)
['', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/usr/local/lib/python3.12/dist-packages', '/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages', '/usr/lib/python3/dist-packages']

配置文件增加对应的路径 “/usr/local/lib/python3.12/dist-packages”

python_lib_path:
  - "/usr/lib/python3.12"
  - "/usr/local/lib/python3.12/dist-packages"
  - "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages"
  - "/usr/lib/x86_64-linux-gnu"
  - "/etc/ssl/certs/ca-certificates.crt"
  - "/etc/nsswitch.conf"
  - "/etc/hosts"
  - "/etc/resolv.conf"
  - "/etc/localtime"
  - "/usr/share/zoneinfo"
  - "/etc/timezone"

再次执行测试 go test -timeout 120s -v ./tests/integration_tests/...

=== RUN   TestPythonPath
    python_feature_test.go:68: TestPythons:&{0 success 0xc000418fe0}
    python_feature_test.go:70: TestPythons stdout: ['/var/sandbox/sandbox-python/tmp', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/usr/local/lib/python3.12/dist-packages', '/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages', '/usr/lib/python3/dist-packages']
        
--- PASS: TestPythonPath (0.05s)

还是有错误

=== RUN   TestPythonRequests
2026/04/26 21:13:18 ERROR process finished with error status="exit status 42"
    python_feature_test.go:96: unexpected error: ==================================================
        Code execution failed with exception:
        ==================================================
        Exception type: ConnectionError
        Exception message: HTTPSConnectionPool(host='www.bilibili.com', port=443): Max retries exceeded with url: / (Caused by NameResolutionError("HTTPSConnection(host='www.bilibili.com', port=443): Failed to resolve 'www.bilibili.com' ([Errno -3] Temporary failure in name resolution)"))
        --------------------------------------------------
        Traceback:
        ool.py", line 787, in urlopen
            response = self._make_request(
                       ^^^^^^^^^^^^^^^^^^^
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 488, in _make_request
            raise new_e
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 464, in _make_request
            self._validate_conn(conn)
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 1093, in _validate_conn
            conn.connect()
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/urllib3/connection.py", line 759, in connect
            self.sock = sock = self._new_conn()
                               ^^^^^^^^^^^^^^^^
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/urllib3/connection.py", line 211, in _new_conn
            raise NameResolutionError(self.host, self, e) from e
        urllib3.exceptions.NameResolutionError: HTTPSConnectiool.py", line 787, in urlopen
            response = self._make_request(
                       ^^^^^^^^^^^^^^^^^^^
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 488, in _make_request
            raise new_e
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 464, in _make_request
            self._validate_conn(conn)
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/urllib3/connectionpool.py", line 1093, in _validate_conn
            conn.connect()
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/urllib3/connection.py", line 759, in connect
            self.sock = sock = self._new_conn()
                               ^^^^^^^^^^^^^^^^
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/urllib3/connection.py", line 211, in _new_conn
            raise NameResolutionError(self.host, self, e) from e
        urllib3.exceptions.NameResolutionError: HTTPSConnectiHTTPSConnection(host='www.bilibili.com', port=443): Failed to resolve 'www.bilibili.com' ([Errno -3] Temporary failure in name resolution)"))
        
        During handling of the above exception, another exception occurred:
        
        Traceback (most recent call last):
          File "/var/sandbox/sandbox-python/tmp/0ed2a15c_105f_4195_a4b1_d5ce0838222a.py", line 53, in <module>
          File "<fd3>", line 3, in <module>
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/requests/api.py", line 73, in get
            return request("get", url, params=params, **kwargs)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/requests/api.py", line 59, in request
            return session.request(method=method, url=url, **kwargs)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/requests/sessions.py", line 592, in request
            resp = self.send(prep, **send_kwargs)
        HTTPSConnection(host='www.bilibili.com', port=443): Failed to resolve 'www.bilibili.com' ([Errno -3] Temporary failure in name resolution)"))
        
        During handling of the above exception, another exception occurred:
        
        Traceback (most recent call last):
          File "/var/sandbox/sandbox-python/tmp/0ed2a15c_105f_4195_a4b1_d5ce0838222a.py", line 53, in <module>
          File "<fd3>", line 3, in <module>
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/requests/api.py", line 73, in get
            return request("get", url, params=params, **kwargs)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/requests/api.py", line 59, in request
            return session.request(method=method, url=url, **kwargs)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/requests/sessions.py", line 592, in request
            resp = self.send(prep, **send_kwargs)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/requests/sessions.py", line 706, in send
            r = adapter.send(request, **kwargs)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          File "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages/requests/adapters.py", line 678, in send
            raise ConnectionError(e, request=request)
        requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.bilibili.com', port=443): Max retries exceeded with url: / (Caused by NameResolutionError("HTTPSConnection(host='www.bilibili.com', port=443): Failed to resolve 'www.bilibili.com' ([Errno -3] Temporary failure in name resolution)"))
        ==================================================
        exit code:42exit status 42error: exit status 42

排查之后发现 缺失文件

root@scd-X99:/var/sandbox/sandbox-python# ll etc/
total 24
drwxr-xr-x 3 root root 4096 Apr 26 20:04 ./
drwxr-xr-x 6 scd  scd  4096 Apr 26 21:13 ../
-rw-r--r-- 2 root root  307 Dec 21 14:32 hosts
lrwxrwxrwx 1 root root   33 Apr 26 20:04 localtime -> /usr/share/zoneinfo/Asia/Shanghai
-rw-r--r-- 2 root root  594 Feb 15  2025 nsswitch.conf
lrwxrwxrwx 1 root root   39 Apr 26 20:04 resolv.conf -> ../run/systemd/resolve/stub-resolv.conf
drwxr-xr-x 3 root root 4096 Apr 22 22:48 ssl/
-rw-r--r-- 2 root root   14 Apr  3 14:24 timezone

在配置文件增加对应的路径 /run/systemd/resolve/stub-resolv.conf

app:
  port: 8194
  debug: True
  key: dify-sandbox
max_workers: 4
max_requests: 50
worker_timeout: 5
python_path: python
nodejs_path: /usr/local/node-v24.14.1/bin/node
python_lib_path:
  - "/usr/lib/python3.12"
  - "/usr/local/lib/python3.12/dist-packages"
  - "/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages"
  - "/usr/lib/x86_64-linux-gnu"
  - "/etc/ssl/certs/ca-certificates.crt"
  - "/etc/nsswitch.conf"
  - "/etc/hosts"
  - "/etc/resolv.conf"
  - "/run/systemd/resolve/stub-resolv.conf"
  - "/etc/localtime"
  - "/usr/share/zoneinfo"
  - "/etc/timezone"
enable_network: True # please make sure there is no network risk in your environment
enable_preload: False # please keep it as False for security purposes
log_path: "./logs" # path to store log files, default is "./logs"
allowed_syscalls: 
proxy:
  socks5: ''
  http: ''
  https: ''

按照上面的配置,测试通过

(.dify-sandbox-python3) root@scd:/home/scd/code/go/dify/dify-sandbox# go test -timeout 120s -v ./tests/integration_tests/...
2026/04/26 21:23:49 INFO initializing nodejs runner environment
2026/04/26 21:23:49 INFO nodejs runner environment initialized
2026/04/26 21:23:49 INFO initializing python runner environment
2026/04/26 21:23:49 INFO network has been enabled
=== RUN   TestNodejsBase64
2026/04/26 21:23:49 INFO sandbox UID entries verified range=10000-10999 count=1000
--- PASS: TestNodejsBase64 (3.43s)
=== RUN   TestNodejsJSON
--- PASS: TestNodejsJSON (3.39s)
=== RUN   TestNodejsFd3Transport
--- PASS: TestNodejsFd3Transport (0.11s)
=== RUN   TestNodejsRunCommand
2026/04/26 21:23:56 ERROR process finished with error status="signal: bad system call (core dumped)"
--- PASS: TestNodejsRunCommand (0.30s)
=== RUN   TestNodejsRunRedeclareFunctionCommand
--- PASS: TestNodejsRunRedeclareFunctionCommand (0.12s)
=== RUN   TestPythonBase64
--- PASS: TestPythonBase64 (2.34s)
=== RUN   TestPythonJSON
--- PASS: TestPythonJSON (2.31s)
=== RUN   TestPythonPath
    python_feature_test.go:68: TestPythons:&{0 success 0xc00009d3c0}
    python_feature_test.go:70: TestPythons stdout: ['/var/sandbox/sandbox-python/tmp', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/usr/local/lib/python3.12/dist-packages', '/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages', '/usr/lib/python3/dist-packages']
        
--- PASS: TestPythonPath (0.05s)
=== RUN   TestPythonRequests
2026/04/26 21:24:01 ERROR process finished with error status="signal: bad system call (core dumped)"
    python_feature_test.go:96: unexpected error: exit code:-1signal: bad system call (core dumped)error: operation not permitted
        
--- FAIL: TestPythonRequests (0.37s)
=== RUN   TestPythonHttpx
--- PASS: TestPythonHttpx (0.39s)
=== RUN   TestPythonTimezone
2026/04/26 21:24:02 ERROR process finished with error status="signal: bad system call (core dumped)"
    python_feature_test.go:144: unexpected error: exit code:-1signal: bad system call (core dumped)error: operation not permitted
        
--- FAIL: TestPythonTimezone (0.22s)
=== RUN   TestPythonFd3Transport
--- PASS: TestPythonFd3Transport (0.05s)
=== RUN   TestPythonLargeOutput
--- PASS: TestPythonLargeOutput (0.27s)
=== RUN   TestSysFork
--- PASS: TestSysFork (0.05s)
=== RUN   TestExec
2026/04/26 21:24:02 ERROR process finished with error status="signal: bad system call (core dumped)"
--- PASS: TestExec (0.22s)
=== RUN   TestRunCommand
2026/04/26 21:24:02 ERROR process finished with error status="signal: bad system call (core dumped)"
--- PASS: TestRunCommand (0.22s)
=== RUN   TestReadEtcPasswd
2026/04/26 21:24:03 ERROR process finished with error status="exit status 42"
--- PASS: TestReadEtcPasswd (0.05s)
FAIL
FAIL	github.com/langgenius/dify-sandbox/tests/integration_tests	13.945s
FAIL
(.dify-sandbox-python3) root@scd-X99:/home/scd/code/go/dify/dify-sandbox# go test -timeout 120s -v ./tests/integration_tests/...
2026/04/26 21:25:50 INFO initializing nodejs runner environment
2026/04/26 21:25:50 INFO nodejs runner environment initialized
2026/04/26 21:25:50 INFO initializing python runner environment
2026/04/26 21:25:50 INFO network has been enabled
=== RUN   TestNodejsBase64
2026/04/26 21:25:50 INFO sandbox UID entries verified range=10000-10999 count=1000
--- PASS: TestNodejsBase64 (3.37s)
=== RUN   TestNodejsJSON
--- PASS: TestNodejsJSON (3.39s)
=== RUN   TestNodejsFd3Transport
--- PASS: TestNodejsFd3Transport (0.11s)
=== RUN   TestNodejsRunCommand
2026/04/26 21:25:57 ERROR process finished with error status="signal: bad system call (core dumped)"
--- PASS: TestNodejsRunCommand (0.28s)
=== RUN   TestNodejsRunRedeclareFunctionCommand
--- PASS: TestNodejsRunRedeclareFunctionCommand (0.11s)
=== RUN   TestPythonBase64
--- PASS: TestPythonBase64 (2.32s)
=== RUN   TestPythonJSON
--- PASS: TestPythonJSON (2.44s)
=== RUN   TestPythonPath
    python_feature_test.go:68: TestPythons:&{0 success 0xc00009cda0}
    python_feature_test.go:70: TestPythons stdout: ['/var/sandbox/sandbox-python/tmp', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/usr/local/lib/python3.12/dist-packages', '/home/scd/code/go/dify/.dify-sandbox-python3/lib/python3.12/site-packages', '/usr/lib/python3/dist-packages']
        
--- PASS: TestPythonPath (0.05s)
=== RUN   TestPythonRequests
--- PASS: TestPythonRequests (0.37s)
=== RUN   TestPythonHttpx
--- PASS: TestPythonHttpx (0.31s)
=== RUN   TestPythonTimezone
--- PASS: TestPythonTimezone (0.05s)
=== RUN   TestPythonFd3Transport
--- PASS: TestPythonFd3Transport (0.04s)
=== RUN   TestPythonLargeOutput
--- PASS: TestPythonLargeOutput (0.27s)
=== RUN   TestSysFork
--- PASS: TestSysFork (0.05s)
=== RUN   TestExec
2026/04/26 21:26:04 ERROR process finished with error status="signal: bad system call (core dumped)"
--- PASS: TestExec (0.22s)
=== RUN   TestRunCommand
2026/04/26 21:26:04 ERROR process finished with error status="signal: bad system call (core dumped)"
--- PASS: TestRunCommand (0.22s)
=== RUN   TestReadEtcPasswd
2026/04/26 21:26:04 ERROR process finished with error status="exit status 42"
--- PASS: TestReadEtcPasswd (0.05s)
PASS
ok  	github.com/langgenius/dify-sandbox/tests/integration_tests	13.705s

测试过程中调整的系统的调用

nodejs
在这里插入图片描述
python
在这里插入图片描述
操作系统信息

$ cat /etc/os-release 
PRETTY_NAME="Ubuntu 24.04.4 LTS"
NAME="Ubuntu"
VERSION_ID="24.04"
VERSION="24.04.4 LTS (Noble Numbat)"
VERSION_CODENAME=noble
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=noble
LOGO=ubuntu-logo

$ uname -a
Linux scd-X99 6.17.0-22-generic #22~24.04.1-Ubuntu SMP PREEMPT_DYNAMIC Thu Mar 26 15:25:54 UTC 2 x86_64 x86_64 x86_64 GNU/Linux
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐