简体   繁体   中英

Start & stop a service as administrator using python

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!

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM