Python monitoring Windows service
wmi
Python can use the module to monitor Windows services on Windows systems . This article will introduce how to use Python to monitor Windows services, and implement service status query and service start and stop functions.
install dependencies
Before using wmi
the module, the wmi package needs to be installed first. It can be installed with the following command:
pip install wmi
Query service status
Use wmi
the module to query the existing services in the Windows system and the running status of the services. The sample code is as follows:
import wmi
# 获取服务状态
def get_service_status(service_name):
wmiobj = wmi.WMI()
services = wmiobj.Win32_Service(Name = service_name)
print(services[0].state)
return services[0].state
# 查询系统中所有服务
def query_all_services():
wmiobj = wmi.WMI()
services = wmiobj.Win32_Service()
for i in services:
print(i)
Start and stop services
os
The service can be started and stopped using the module. The specific method is as follows:
import os
import ctypes
#判断是否有管理员权限
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
# 启动服务
def start_service(service_name):
if is_admin():
cmd = 'NET START {}'.format(service_name)
result = os.popen(cmd)
print(result)
else:
print('no admin')
# 停止服务
def stop_service(service_name):
if is_admin():
cmd = 'NET STOP {}'.format(service_name)
result = os.popen(cmd)
print(result)
else:
print('no admin')
Get memory information
Use psutil
the module to obtain memory information. The specific method is as follows:
# -*- encoding: utf-8 -*-
# 获取内存信息
def get_memory_info():
memory_info = {
}
mem_info = psutil.virtual_memory()
memory_info['total'] = mem_info.total
memory_info['available'] = mem_info.available
memory_info['percent'] = mem_info.percent
memory_info['used'] = mem_info.used
memory_info['free'] = mem_info.free
print(memory_info)
print(memory_info['percent'])
sample code
Attached is a complete sample code that demonstrates how to query all services in the system and start and stop services:
summary
This article introduces how to use Python to monitor Windows services, and realizes the query of service status and the function of starting and stopping services. If you need to manage Windows services, you can use the code provided in this article as a reference.