我想在Python中运行一些代码。但是,出于安全考虑,我需要在某种沙盒中运行它。我正在做的是: 首先,我创建一个具有受限权限的域:
private AppDomain CreateDomain()
{
AppDomainSetup setup = new AppDomainSetup();
Assembly thisAssembly = Assembly.GetExecutingAssembly();
setup.ApplicationBase = Path.GetDirectoryName(thisAssembly.Location);
AssemblyName name = typeof(Program).Assembly.GetName();
StrongName sn = new StrongName(new StrongNamePublicKeyBlob(name.GetPublicKey()), name.Name, name.Version);
PermissionSet permSet = new PermissionSet(PermissionState.None);
permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
setup.PartialTrustVisibleAssemblies = new[] { sn.Name + ", PublicKey=" + sn.PublicKey.ToString() };
AppDomain domain = AppDomain.CreateDomain(
"Sandbox",
AppDomain.CurrentDomain.Evidence,
setup,
permSet,
sn);
return domain;
}
接下来我创建python引擎和其他所需的项目(d是我在python中工作的字典:
string pythonCode = File.ReadAllText(@"D:\Python\Class.py");
string createInstanceCode = "ObjectNew = Class(dictionary)";
ScriptEngine pyEngine = IronPython.Hosting.Python.CreateEngine(domain);
ScriptScope pyScope = pyEngine.CreateScope();
pyScope.SetVariable("dictionary", d);
pyEngine.Execute(pythonCode, pyScope);
pyEngine.Execute(createInstanceCode, pyScope);
python代码只是一个包含函数的大类。我想从C#调用这些函数并获得结果,所以我尝试创建该类的实例。使用这个问题的建议:How do I call a specific Method from a Python Script in C#?我这样做:
var testObject = pyScope.GetVariable("ObjectNew");
这是我在这一点上得到的错误: 类型为' System.Runtime.Serialization.SerializationException'的未处理异常发生在PythonTimeTests.exe
如果我改变这个
,这不会发生ScriptEngine pyEngine = IronPython.Hosting.Python.CreateEngine(domain);
到
ScriptEngine pyEngine = IronPython.Hosting.Python.CreateEngine();
但是我无法管理IronPython的权限。有没有一种方法可以在没有序列化的情况下以不同的方式执行此操作或者是否有一种更好的沙盒方法(也许沙盒管理IronPython的整个C#代码)?