1

I'm writing a Python script (on Windows) which must be run under an elevated CMD (because it runs a subprocess call which must have administrator privileges).

However - inside the script, there's a part which doesn't work when run as admin, but does work when run as a normal user (accessing a mapped network drive).

I would like to un-elevate the script for a particular part, or just in the middle of it.

Also, since the script wil be run in an automated way, I would like no need for user clicking or input during the script.

For example:

do_stuff_as_user_x_admin()
un_elevate()
do_stuff_as_user_x_non_admin()

How can I achieve this?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • can you use `sudo` for the privileged parts? – L.Grozinger Jul 19 '20 at 11:41
  • @L.Grozinger I don't have `sudo`, running on Windows :) – Aviv Cohn Jul 19 '20 at 11:46
  • If you have control of the system, it may be simpler in general to enable linked drive mappings. Otherwise you'll have this problem everywhere. But if you want to proceed with the current approach, you can impersonate the standard-access token in the current thread. – Eryk Sun Jul 19 '20 at 11:46
  • Note that this isn't a duplicate of https://stackoverflow.com/q/8025294/674064, as this question is about Windows while https://stackoverflow.com/q/8025294/674064 is about Linux. – das-g Jul 19 '20 at 11:48
  • have you seen http://code.kliu.org/misc/elevate/ ? – L.Grozinger Jul 19 '20 at 11:55
  • I should note that impersonation of the standard-access token isn't exactly the same as "un-elevate", so that would be a bad name. For some operations, the system always uses the process token (e.g. `CreateProcessW` as used by `subprocess.Popen`). But impersonation works fine for file and registry access (except not as a workaround for app-container redirection if you're in an app sandbox) . In particular, you'll have the impersonated logon's drive mapping. – Eryk Sun Jul 19 '20 at 12:08

0 Answers0