3

I'm attempting to use python to trigger a Powershell script which runs fine when I run it from my connection to Powershell (which defaults to 'run as administrator). However, when launched from a python interface, it give me a permission denied error. Here's a snippet of some of the code I'm attempting to run which fails when launched by Python but not when launched through a powershell prompt.

elif "!ExchangeCheck" in message:
    response = subprocess.Popen("powershell -ExecutionPolicy Unrestricted -File C:\users\.....\code\servicecheck.ps1", shell=True, stdout=subprocess.PIPE).stdout.read()
    status = "Exchange services are: \n"
    for line in thing:
        if "Microsoft Exchange" in response:
            status += line
    print status

Hoping to find a way to use Popen or something like paramiko for powershell where it will attempt to 'run as administrator' or at least use my native permissions when it attempts to run?

UPDATE: I have verified that my python script is running as an admin user.

UPDATE 2: I think a solution would be to run a script using the runas command to accretive the desired goal but I don't know if that is 'good' way to do things, it seems less than ideal.

Abraxas
  • 341
  • 1
  • 9
  • 28
  • Is the Python process running with elevated privileges? – jpmc26 May 31 '16 at 19:52
  • @jpmc26 I have an admin console from which I launch the python script. So from admin command prompt --> python program.py – Abraxas May 31 '16 at 21:44
  • Trying the code [here](http://stackoverflow.com/a/1026626/1394393) to check if your Python process has admin rights. – jpmc26 May 31 '16 at 21:48
  • @jpmc26 Response is true when launching that file like I launch my script. I'm guessing it's when my script tries to launch powershell is where the permissions are dropping out =( – Abraxas May 31 '16 at 21:53

1 Answers1

0

what if you try to invoke a subprocess with enough privileges? I think the ctypes library can help you in that task (just trythis decorator)

def elevate_process(funct):
"""
Decorator to elevate privileges of a function on windows systems, it will create a sub process with administration privileges when the wrapper detects there is not enough privileges.
"""
import sys
def wrapper(*args, **kwargs):
    import ctypes
    import subprocess
    validation = ctypes.windll.shell32.IsUserAnAdmin()
    if validation == 1:
        return funct(*args, **kwargs)
    else:
        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
return wrapper