3

So, I want to run a program in administrator mode (UAC)

After some digging i foud this:

import os
import types
from traceback import print_exc
from sys import argv, executable




def isUserAdmin():

    if os.name == 'nt':
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            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 = executable

    if cmdLine is None:
        cmdLine = [python_exe] + 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: ", argv
        #rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
        rc = runAsAdmin()
    else:
        print "You are an admin!", os.getpid(), "params: ", argv
        rc = 0
    x = raw_input('Press Enter to exit.')
    return rc
if __name__ == "__main__":
    if not isUserAdmin():
        runAsAdmin()

Which asks the user for admin. permission,but i have two main problems with it:

1.The user needs to give the program permission.(Problematic for pentesting)

2.Every time the program is run the user needs to give the program permission.(which is suspicious)

Is there a way to bypass this?

ps. windows 7 and no direct access

Richard Paul Astley
  • 323
  • 3
  • 7
  • 18
  • Does Windows 7 have anything in the file properties or control panel to automatically allow certain programs to default to elevated privileges? – NuclearPeon Jul 17 '15 at 16:36
  • 1
    Only a system service can bypass UAC to elevate an administrator. For example, the task scheduler service does this when highest privileges are requested. So you can just create a task to run on demand. – Eryk Sun Jul 17 '15 at 16:44

1 Answers1

2

Assuming you have access to the computers this script is running on then you can follow the instructions in this link...

http://www.howtogeek.com/124087/how-to-create-a-shortcut-that-lets-a-standard-user-run-an-application-as-administrator/

It will allow a standard user to run a particular application as an administrator. I've used this guide successfully on other apps but never on a python script. Might work for you.

abaldwin99
  • 903
  • 1
  • 8
  • 26
  • Is there a way to Create A Task on Task Scheduler from a python script? – Richard Paul Astley Jul 17 '15 at 17:12
  • 1
    Well you can create a scheduled task from windows cmd shell using `schtasks`. So you in theory you should be able to use python's subprocess to run a schtasks command. Here's a link talking about doing just that... http://stackoverflow.com/questions/2725754/schedule-python-script-windows-7 – abaldwin99 Jul 17 '15 at 17:27
  • 1
    @RichardPaulAstley, when creating the task use the option `/rl highest` to make it run elevated. Then run the task on demand via `schtasks.exe /run /tn [taskname]`. – Eryk Sun Jul 17 '15 at 17:37