Pysandbox setup issues

I have two questions regarding Pysandbox:

  • How to achieve functionality eval? I understand that it is sandbox.execute()equivalent exec, but I can’t find anything that if the entered code was 2 + 2, it would return 4or something like that.

  • By default, sandbox.execute()it makes the environment with read-only access enabled, i.e. if I execute sandbox.execute('data.append(4)', locals={'data': [1, 2, 3]}), an error will occur. How to make portable read-write media?

+3
source share
2 answers

Yeah, I see that the latest version of PySandbox (1.5) behaves the way you describe. I tried the git master branch.

1, , PySandbox 1.5 . , - . sandbox.call(eval, CODE) , locals globals ( , , eval() , dicts). , , .

2 , . git, , - :)

, , , , , , , :

from sandbox.proxy import proxy
from sandbox.sandbox_class import _call_exec

def proxyNamespace(d):
    return dict((str(k), proxy(v)) for k, v in d.iteritems())

def wrapeval(codestr, globs, locs):
    subglobs = proxyNamespace(globs)
    sublocs = proxyNamespace(locs)
    return eval(codestr, subglobs, sublocs)

def eval_in_sandbox(sandbox, codestr, globs=None, locs=None):
    if globs is None:
        globs = {}
    if locs is None:
        locs = globs
    return sandbox._call(wrapeval, (codestr, locs, globs), {})

def exec_in_sandbox_with_mutable_namespace(sandbox, codestr, globs=None, locs=None):
    if globs is None:
        globs = {}
    if locs is None:
        locs = globs
    subglobs = proxyNamespace(globs)
    sublocs = proxyNamespace(locs)
    sandbox._call(_call_exec, (codestr, subglobs, sublocs), {})
    globs.update(subglobs)
    locs.update(sublocs)

, , , - PySandbox. , , . , , , . , . , - , , AppArmor - . , , , .

+1

1:

sandbox.call(eval, "2+2")

2:

from sandbox import Sandbox, SandboxConfig
cfg=SandboxConfig('stdout')
import sys

out1 = sys.stdout
err1 = sys.stderr
with open("logfile.txt", "w") as f:    
    sys.stdout = sys.stderr = f
    sandbox = Sandbox(cfg)
    indata={'data': [1, 2, 3]}
    sandbox.execute('a=list(data);a.append(4); print(str(a))', locals=indata)

sys.stdout = out1
sys.stderr = err1

with open("logfile.txt", "r") as f: 
    indata=eval(f.read())
    print indata

2. Readable-Writebale . .

:

$ python test.py 
[1, 2, 3, 4]
0

All Articles