2

I am using a python script and win32serviceutil module in order to stop and start Windows services. My account is a member of group 'local administrators'. I login with that account and run the script but get the error: Access denied.

If I start a cmd prompt as Administrator and the run from that window it works fine.

My question:

  • How could I specify inside the script to run it as an administrator? (note: I don't know administrator password)
LightCC
  • 9,804
  • 5
  • 52
  • 92
susja
  • 311
  • 3
  • 12
  • 33
  • This could help >>> http://stackoverflow.com/questions/19672352/how-to-run-python-script-with-elevated-privilage-on-windows – Syed Mauze Rehan Dec 17 '14 at 06:04
  • If you define `HKCR\Python.File\shell\runas\command` in the registry, then you can launch the script elevated via `os.startfile(__file__, 'runas')`. Just copy the command from `HKCR\Python.File\shell\open\command`. The user will get a UAC prompt to elevate. Test to see whether it's necessary by calling `ctypes.windll.shell32.IsUserAnAdmin()`. For passing command-line arguments you'll have to use `ShellExecuteEx` instead, via ctypes or PyWin32, as linked above. – Eryk Sun Dec 17 '14 at 06:51
  • I resolve my issue by looking into one of the topics on stackoverflow.com It suggested to use batch file which will call python script and on the top of that batch use PowerShell command to elevate privilage. It worked for me. Ticket could be closed – susja Dec 18 '14 at 02:39

1 Answers1

1

If you don't know the administrator password then you cannot execute your python script with elevated privilege!

Reason: The solutions available for executing the python script with elevated privilege will simply prompt the UAC. Then you have to provide the administrator password and if the password is correct your script will execute with administrator privilege. So, ultimately you must know the administrator password!

Also the reason why you need an administrator password is that it would be a security risk that you can execute any script with administrator privilege without having the administrator rights. Just think if any one can execute any script on your computer from the guest account. Hope it helped.

ρss
  • 5,115
  • 8
  • 43
  • 73
  • Well ... since my account is in local admin group I could from Start menu right click on cmd icon and select option 'Run as Administrator'. This starts cmd prompt and all commands are executed "as administrator' But I need to do this from inside the script Hence in my case manually I could run 'as administrator' without knowing the password. My problem is how to do it from inside the script automatically – susja Dec 17 '14 at 12:34