How to run a subprocess with admin permission?

Asked

Viewed 2,696 times

4

I’m making a script that accesses the cmd windows, via subprocess. Only I need to rotate the cmd as an administrator.

The solution I found, does not satisfy me, which would be to use the runas. What I want to know is if there is any way to acquire administrator status inside the script, no need run as administrator. Is there any way?

  • I find it difficult. In theory this is impossible for security.

  • So, I don’t know, it would be something equivalent to sudo linux.

  • 1

    If you schedule a task with administrator credentials, you can allow any user to run it with high privileges without needing a password.

2 answers

2


After some time searching the internet, I found in SOEN that answer who basically does what I want.

It speaks of a script created by Preston Landers, which executes the runas, proposed by @utluiz within the . Follows code from the module:

#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4

# (C) COPYRIGHT © Preston Landers 2010
# Released under the same license as Python 2.6.5


import sys, os, traceback, types

def isUserAdmin():

    if os.name == 'nt':
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            print "Admin check failed, assuming not an admin."
            return False
    elif os.name == 'posix':
        # Check for root on Posix
        return os.getuid() == 0
    else:
        raise RuntimeError, "Unsupported operating system for this module: %s" % (os.name,)

def runAsAdmin(cmdLine=None, wait=True):

    if os.name != 'nt':
        raise RuntimeError, "This function is only implemented on Windows."

    import win32api, win32con, win32event, win32process
    from win32com.shell.shell import ShellExecuteEx
    from win32com.shell import shellcon

    python_exe = sys.executable

    if cmdLine is None:
        cmdLine = [python_exe] + sys.argv
    elif type(cmdLine) not in (types.TupleType,types.ListType):
        raise ValueError, "cmdLine is not a sequence."
    cmd = '"%s"' % (cmdLine[0],)
    # XXX TODO: isn't there a function or something we can call to massage command line params?
    params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
    cmdDir = ''
    showCmd = win32con.SW_SHOWNORMAL
    #showCmd = win32con.SW_HIDE
    lpVerb = 'runas'  # causes UAC elevation prompt.

    # print "Running", cmd, params

    # ShellExecute() doesn't seem to allow us to fetch the PID or handle
    # of the process, so we can't get anything useful from it. Therefore
    # the more complex ShellExecuteEx() must be used.

    # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)

    procInfo = ShellExecuteEx(nShow=showCmd,
                              fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                              lpVerb=lpVerb,
                              lpFile=cmd,
                              lpParameters=params)

    if wait:
        procHandle = procInfo['hProcess']    
        obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
        #print "Process handle %s returned code %s" % (procHandle, rc)
    else:
        rc = None

    return rc

def test():
    rc = 0
    if not isUserAdmin():
        print "You're not an admin.", os.getpid(), "params: ", sys.argv
        #rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
        rc = runAsAdmin()
    else:
        print "You are an admin!", os.getpid(), "params: ", sys.argv
        rc = 0
    x = raw_input('Press Enter to exit.')
    return rc


if __name__ == "__main__":
    sys.exit(test())

It is worth noting that this script is only valid for Windows XP SP 2 or superior.

  • 1

    Interesting approach!

1

Windows has a command called runas. Typing this command without parameters in cmd Windows XP, get the following help:

RUNAS USAGE:

RUNAS [ [/noprofile | /profile] [/env] [/netonly] ]
        /user:<UserName> program

RUNAS [ [/noprofile | /profile] [/env] [/netonly] ]
        /smartcard [/user:<UserName>] program

   /noprofile        specifies that the user's profile should not be loaded.
                     This causes the application to load more quickly, but
                     can cause some applications to malfunction.
   /profile          specifies that the user's profile should be loaded.
                     This is the default.
   /env              to use current environment instead of user's.
   /netonly          use if the credentials specified are for remote
                     access only.
   /savecred         to use credentials previously saved by the user.
                     This option is not available on Windows XP Home Edition
                     and will be ignored.
   /smartcard        use if the credentials are to be supplied from a
                     smartcard.
   /user             <UserName> should be in form USER@DOMAIN or DOMAIN\USER
   program         command line for EXE.  See below for examples

Examples:
> runas /noprofile /user:mymachine\administrator cmd
> runas /profile /env /user:mydomain\admin "mmc %windir%\system32\dsa.msc"
> runas /env /user:[email protected] "notepad \"my file.txt\""

NOTE:  Enter user's password only when prompted.
NOTE:  USER@DOMAIN is not compatible with /netonly.
NOTE:  /profile is not compatible with /netonly.

Therefore, I believe you could run the following command from Python:

runas /profile /user:<domínio>\<administrador> "cmd ..."

Being:

  • <domínio> the domain name or local machine name; and
  • <administrador> the user name with administrative privileges.

Note that the user will be required to enter the administrator’s credentials. However, this can be mitigated with the option /savecred, which uses previously saved credentials. But you need to check if your Windows version supports the option.

  • This would be for me to rotate open one cmd as an administrator, not to gain "administrator status". This is equivalent to right-clicking and running as an administrator.

  • @Felipeavelar The solution to "Rotate the cmd as administrator" and this, can not circumvent authentication of the Operating System. I searched a little more and found this issue in the SOEN. Take a look at the first two answers.

  • but this command is to open another cmd with privilege, I wanted to give the privileges to the subprocess of Python. I know it is possible to do from of that answer, but I wanted like a sudo, since I don’t know how to apply this in Python. :/

  • 1

    @Felipeavelar From what they say can not do this. I at least have no idea of other alternatives. Sorry...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.