0

I want to start/stop a service (eg. someService) as administrator using Python in Windows. Right now I can think of two ways is either (1) using command lines in python codes (2) use some module to achieve this purpose directly in Python way.

I've tried the following codes but it returned "Access Denied".

import os

cmd = r"net stop someService"
os.system(cmd)

If anyone how to solve this, pls let me know thanks!

ryan9025
  • 267
  • 6
  • 17
  • Just a start/stop service? also, what platform are you referring? it's different impl. on Win or Linux (I assume windows, since you are running as admin and not as root) – Chen A. Oct 02 '17 at 09:15
  • @Vinny Yes just to start/stop a service. Also it's in Windows. – ryan9025 Oct 02 '17 at 09:17
  • 2
    Possible duplicate of [How to run python script with elevated privilege on windows](https://stackoverflow.com/questions/19672352/how-to-run-python-script-with-elevated-privilege-on-windows) – Null Oct 02 '17 at 09:43

1 Answers1

0

You can use this function which takes the name of the service as first param and the action second. You need to use the runas windows command to execute a command using a different user.

import os

def toggle_service(name, action):
    cmd = 'runas /noprofile /user:administrator "net {} \'{}\'"'.format(action, name)
    os.system(cmd)

To run it for example use toggle_service('Print Spooler', 'start')

Chen A.
  • 10,140
  • 3
  • 42
  • 61