Skip to content

Instantly share code, notes, and snippets.

@nomissbowling
Created May 26, 2026 03:10
Show Gist options
  • Select an option

  • Save nomissbowling/87f031401be4838835cfcfef5a6ae2ba to your computer and use it in GitHub Desktop.

Select an option

Save nomissbowling/87f031401be4838835cfcfef5a6ae2ba to your computer and use it in GitHub Desktop.
test_restart_svc.py
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
'''test_restart_svc
runas /user:administrator "python ./test_restart_svc.py"
'''
import sys, os
import subprocess
from subprocess import PIPE
import time
def proc(cl, cwd, enc):
p = subprocess.run(cl, stdout=PIPE, stderr=PIPE, cwd=cwd)
se = p.stderr.decode(enc)
if len(se) > 0: print(se)
so = p.stdout.decode(enc)
if len(so) > 0: print(so)
return so, se
def proc_tasklist(so, exen):
pid = 0
PID_SEP = '========'
PID_HEAD, PID_LEN = 26, len(PID_SEP)
PID_END = PID_HEAD + PID_LEN
phase = False
for l in so.split('\x0A'):
t = l.rstrip() if l.endswith('\x0D') else l
if len(t) < PID_END: continue
if not phase:
if t[PID_HEAD:PID_END] == PID_SEP: phase = True
else:
if not t.startswith(exen): continue
try:
pid = int(t[PID_HEAD:PID_END])
break
except (e, ):
continue
return pid
def task_list(svcn, exen, cwd, enc):
# cl = ['tasklist', '/fi', f'"services eq {svcn}"']
cl = f'tasklist /fi "services eq {svcn}"'
so, se = proc(cl, cwd, enc)
if len(so) == 0: return
pid = proc_tasklist(so, exen)
if pid == 0: return None
print(pid)
return pid
def task_kill(pid, cwd, enc):
cl = f'taskkill /f /pid {pid}'
so, se = proc(cl, cwd, enc)
# if len(so) == 0: return
def net_start(svcn, cwd, enc):
cl = f'net start {svcn}'
so, se = proc(cl, cwd, enc)
# if len(so) == 0: return
def restart_svc(svcn, exen, enc):
cwd = os.getenv('tmp', '~/tmp')
pid = task_list(svcn, exen, cwd, enc)
task_kill(pid, cwd, enc)
net_start(svcn, cwd, enc)
pid = task_list(svcn, exen, cwd, enc)
time.sleep(5)
if __name__ == '__main__':
restart_svc('wlansvc', 'svchost.exe', 'cp932')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment