'How to stop windows service as administrator in python?

I already tried a few ways but none of them worked.

os.system('net stop service_name')

which returns "System error 5 has occurred. Access denied.

os.system('runas /user:Administrator net stop service_name')

no errors, but nothing happened

subprocess.Popen(
    ['runas', '/user:Administrator', 'net stop service_name'],
    stdin=subprocess.PIPE
)
process.stdin.write(b'admin_password_here')

again nothing happened

win32serviceutil.StopService(service_name)

and few more ways



Solution 1:[1]

try add noprofile:

import os
service_name = ''
action = "stop"
os.system(f'runas /noprofile /user:administrator "net {action} '{service_name}'"')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tal Folkman