如果一个程序被服务监管,那么仅仅kill程序是无用的,还要把服务关掉
import win32service
import win32serviceutildef EnableService(service_name):try:# 获取服务管理器scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)# 获取服务的句柄service = win32service.OpenService(scm, service_name, win32service.SERVICE_ALL_ACCESS)# 自启动服务win32service.ChangeServiceConfig(service, win32service.SERVICE_NO_CHANGE, win32service.SERVICE_AUTO_START, win32service.SERVICE_NO_CHANGE, None, None, 0, None, None, None, None)print(f"{service_name} service enabled successfully.")except Exception as e:print(f"Failed to enable {service_name} service. Error: {e}")finally:# 关闭服务句柄win32service.CloseServiceHandle(service)# 关闭服务管理器句柄win32service.CloseServiceHandle(scm)def StartService(service_name):try:win32serviceutil.StartService(service_name)print(f"{service_name} service started successfully.")except Exception as e:print(f"Failed to start {service_name} service. Error: {e}")def StopService(service_name):try:# 获取服务管理器scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)# 获取服务的句柄service = win32service.OpenService(scm, service_name, win32service.SERVICE_ALL_ACCESS)# 停止服务win32service.ControlService(service, win32service.SERVICE_CONTROL_STOP)print(f"{service_name} service stopped successfully.")except Exception as e:print(f"Failed to stop {service_name} service. Error: {e}")finally:# 关闭服务句柄win32service.CloseServiceHandle(service)# 关闭服务管理器句柄win32service.CloseServiceHandle(scm)def DisableService(service_name):try:# 获取服务管理器scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)# 获取服务的句柄service = win32service.OpenService(scm, service_name, win32service.SERVICE_ALL_ACCESS)# 禁用服务win32service.ChangeServiceConfig(service, win32service.SERVICE_NO_CHANGE, win32service.SERVICE_DISABLED, win32service.SERVICE_NO_CHANGE, None, None, 0, None, None, None, None)print(f"{service_name} service Disabled successfully.")except Exception as e:print(f"Failed to disable {service_name} service. Error: {e}")finally:# 关闭服务句柄win32service.CloseServiceHandle(service)# 关闭服务管理器句柄win32service.CloseServiceHandle(scm)
def Remove_Service(service_name):try:win32serviceutil.RemoveService(service_name)print(f"Service '{service_name}' removed successfully.")except Exception as e:print(f"Failed to remove service '{service_name}'. Error: {e}")service_name = 'PostgreSQL_65432'
# EnableService(service_name)
StartService(service_name)
#StopService(service_name)
#DisableService(service_name)
#Remove_Service(service_name)