Run python script with different user from ASP.Net Core

181 Views Asked by At

With the code below I am executing a python script from an ASP.Net Core app which runs in IIS. I want to run the python script with a different user which has limited rights.

I am able to change the user. I verified this by running the command getpass.getuser() in the script. But the script still has access to parts of the drive which it should not. When running the script via command line and changing the user via runas it works perfectly. The user only as limited access.

How can I restricted the python script from my ASP.Net Core app?

public string ExecutePythonSnippet(string pythonSnippetFilePath, string pkgFilePath, string parameterString, string command = null)
{
    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = pythonPath;
    string argsString = $"\"{pythonSnippetFilePath}\"";
    argsString += $" \"{pkgFilePath}\"";
    argsString += $" \"{parameterString}\"";
    if (command != null)
        argsString += $" \"{command}\"";
    start.Arguments = argsString;
    if (!string.IsNullOrWhiteSpace(_username))
    {
        start.Verb = "runasuser";
        start.UserName = _username;
        start.Password = new NetworkCredential("", _password).SecurePassword;
    }
    start.UseShellExecute = false;// Do not use OS shell
    start.CreateNoWindow = true; // We don't need new window
    start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
    start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
    using (Process process = Process.Start(start))
    {
        using (StreamReader reader = process.StandardOutput)
        {
            string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
            string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
            if (string.IsNullOrEmpty(result))
                return result;
            else
                throw new Exception(result);
        }
    }

EDIT: Changed runas to runasuser but with no success

0

There are 0 best solutions below