3

How do I go about checking whether privelege elevation is required to start a subprocess without trying first then failing?

I need to start a subprocess command from within python code. In some cases it works fine, in other cases it turns out that elevated priveleges are required; and on some windows systems this condition causes my program to freeze.

I would like to determine wether privelege escalation is required without attempting to first run the subprocess and catching / traping any error condition.

The process that causes the program to freeze is invoked with;

subprocess.call('path _ filename _ options',shell=False)

Matt Warren
  • 669
  • 8
  • 18
  • 1
    Impossible to do this 100%. Good start would be to read the app manifest and check for requireAdministrator. – David Heffernan Nov 10 '11 at 11:34
  • Thanks for the hint, I shall investigate further :) – Matt Warren Nov 10 '11 at 13:00
  • What's wrong with checking for failure? EAFP is standard for Python. – Karl Knechtel Nov 10 '11 at 13:53
  • @Karl, True, but in the case I am currently trying to solve, in the failure case the program being run freezes and does not return when the subprocess it is trying to start requires elevated priveleges. The program is trying to be started with subprocess.call('some path and filename and options',shell=False) – Matt Warren Nov 11 '11 at 14:08
  • Maybe just escalate privileges anyway? Shouldn't cause a problem if the user is already an admin, and it sounds like, if you don't always need the escalation, that you can't determine ahead of time whether you will need them anyway... o_O – Karl Knechtel Nov 11 '11 at 14:11

1 Answers1

4

With pywin32, something like the following should work...:

import pythoncom
import pywintypes
import win32api
from win32com.shell import shell

if shell.IsUserAnAdmin():
   ...

And yes, it seems pywin32 does support Python 3.

Written by Alex Martelli

Also this for people without pywin32.

import ctypes
print ctypes.windll.shell32.IsUserAnAdmin()
Community
  • 1
  • 1
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
  • HI, I did see this, but for some reasons and others I am unable to use pywin32 in this instance :/ – Matt Warren Nov 10 '11 at 13:00
  • Hold on I think you can do the same in ctypes – Jakob Bowyer Nov 10 '11 at 13:02
  • I saw that too.. But it involves using CreateProcess() and detecting wether this fails or not (If we are reading from the same stackoverflow question and subsequent link ;P). I am thinking of at least trying the ctypes method, as it may not result in the same 'freeze' on the error condition as I get on failure in some cases at the moment. I haven't used ctypes in that way previously so I don;t know how / if it will have the same behaviour I am seeing at the moment. – Matt Warren Nov 10 '11 at 13:29