3

We were using python 2 in our project and we had created various scripts that work on Windows 10 using pywin32 lib and were using import win32com.shell.shell as shell and then execute the shell commands like shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c ' + commands) where commands is the command which we use to execute as admin prompt.

Our script needs to do some installation which we pass as command and recently due to executive decision we have to move to python3 and when I am trying to import import win32com.shell.shell as shell it is not able to import it.

Can someone please suggest how can we execute shell command as admin in python 3.8.3 on Windows 10?

oguz ismail
  • 1
  • 16
  • 47
  • 69
thebadguy
  • 2,092
  • 1
  • 22
  • 31
  • 1
    Does this answer your question? [How to run script with elevated privilege on windows](https://stackoverflow.com/questions/19672352/how-to-run-script-with-elevated-privilege-on-windows) – The Amateur Coder May 17 '23 at 19:20

3 Answers3

2

I know this is old but in case someone still have the same issue you can use from win32comext.shell import shell, as it's mentioned here on github.

SiHa
  • 7,830
  • 13
  • 34
  • 43
Yahia
  • 31
  • 6
0

You can now use the PyUAC module (for Windows, Python 3). Install it using:

pip install pyuac
pip install pypiwin32

Direct usage of the package is:

import pyuac

def main():
    print("Do stuff here that requires being run as an admin.")
    # The window will disappear as soon as the program exits!
    input("Press enter to close the window. >")

if __name__ == "__main__":
    if not pyuac.isUserAdmin():
        print("Re-launching as admin!")
        pyuac.runAsAdmin()
    else:        
        main()  # Already an admin here.

Or, if you wish to use the decorator:

from pyuac import main_requires_admin

@main_requires_admin
def main():
    print("Do stuff here that requires being run as an admin.")
    # The window will disappear as soon as the program exits!
    input("Press enter to close the window. >")

if __name__ == "__main__":
    main()

The actual code (in the module) is:-

#!/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())

(from this answer)

The Amateur Coder
  • 789
  • 3
  • 11
  • 33
-1

win32com.shell.shell as shell would be imported exclusively on python2 if you wanted to upgrade you would have to update to a newer version of pywin32. A github repo has released v225 which supports Python 3.8.3 install the files and you should be able to use your code without any import errors

https://github.com/CristiFati/Prebuilt-Binaries/tree/master/PyWin32/v225

if that does not work that alternative solution is using a replica module

pip3 install pypiwin32


import pypiwin32 

this module should come with shell capabilities

Seaver Olson
  • 450
  • 3
  • 16
  • 1
    I already have pywin32 build 228 installed on my machine still I am facing the issue and even tried with 225 builds which you suggested the import issue is there – thebadguy Jun 29 '20 at 09:42
  • @thebadguy If that did not work then I would try importing win32api which is a replica of pywin32 – Seaver Olson Jun 29 '20 at 09:46
  • can you please suggest the import for this as this module also does not have shell module – thebadguy Jun 29 '20 at 09:58
  • I currently am on my Macbook so I can not test this out but I updated my answer with instructions to install a module with the shell inside hopefully that works – Seaver Olson Jun 29 '20 at 10:34
  • 1
    ERROR: Could not find a version that satisfies the requirement pypiwin32 (from versions: none) ERROR: No matching distribution found for pypiwin32 is coming when using install command – thebadguy Jun 29 '20 at 10:39