def Start(cls): state = cls.__CurrentState() if state is None: print("Service %s is not installed." % cls._svc_name_) return if state == win32service.SERVICE_RUNNING: print("Service %s started already." % cls._svc_name_) return if state == win32service.SERVICE_STOP_PENDING: win32serviceutil.WaitForServiceStatus(cls._svc_name_, win32service.SERVICE_STOPPED, 30) state = win32service.SERVICE_STOPPED elif state == win32service.SERVICE_PAUSE_PENDING: win32serviceutil.WaitForServiceStatus(cls._svc_name_, win32service.SERVICE_PAUSED, 30) state = win32service.SERVICE_PAUSED if state == win32service.SERVICE_STOPPED: win32serviceutil.StartService(cls._svc_name_) elif state == win32service.SERVICE_PAUSED: win32serviceutil.ControlService( cls._svc_name_, win32service.SERVICE_CONTROL_CONTINUE) win32serviceutil.WaitForServiceStatus(cls._svc_name_, win32service.SERVICE_RUNNING, 30) print("Service %s started successfully." % cls._svc_name_)
def start(self, start_driver, driver_exists=False): # we are in native API mode so not starting the service/driver if not start_driver: return True self.use_existing_service = (win32serviceutil.QueryServiceStatus( SERVICE_NAME)[1] == win32service.SERVICE_RUNNING) if self.use_existing_service: self.driver_loaded = True if logger().VERBOSE: logger().log("[helper] service '%s' already running" % SERVICE_NAME) if logger().VERBOSE: logger().log( "[helper] trying to connect to existing '%s' service..." % SERVICE_NAME) else: #if self.use_existing_service: # _handle_error( "connecting to existing '%s' service failed (service is not running)" % SERVICE_NAME ) try: win32serviceutil.StartService(SERVICE_NAME) win32serviceutil.WaitForServiceStatus( SERVICE_NAME, win32service.SERVICE_RUNNING, 1) self.driver_loaded = True if logger().VERBOSE: logger().log("[helper] service '%s' started" % SERVICE_NAME) except pywintypes.error, (hr, fn, msg): _handle_error( "service '%s' didn't start: %s (%d)" % (SERVICE_NAME, msg, hr), hr)
def stop(self, start_driver): if not start_driver: return True if self.use_existing_service: return True if logger().DEBUG: logger().log( "[helper] stopping service '{}'..".format(SERVICE_NAME)) try: win32api.CloseHandle(self.driver_handle) self.driver_handle = None win32serviceutil.StopService(SERVICE_NAME) except pywintypes.error as err: if logger().DEBUG: logger().error("StopService failed: {} ({:d})".format( err.args[2], err.args[0])) return False finally: self.driver_loaded = False try: win32serviceutil.WaitForServiceStatus(SERVICE_NAME, win32service.SERVICE_STOPPED, 1) if logger().DEBUG: logger().log( "[helper] service '{}' stopped".format(SERVICE_NAME)) except pywintypes.error as err: if logger().DEBUG: logger().warn("service '{}' didn't stop: {} ({:d})".format( SERVICE_NAME, err.args[2], err.args[0])) return False return True
def start(self, start_driver, driver_exists=False): # we are in native API mode so not starting the service/driver if not start_driver: return True self.use_existing_service = (win32serviceutil.QueryServiceStatus( SERVICE_NAME)[1] == win32service.SERVICE_RUNNING) if self.use_existing_service: self.driver_loaded = True if logger().DEBUG: logger().log("[helper] service '{}' already running".format( SERVICE_NAME)) logger().log( "[helper] trying to connect to existing '{}' service...". format(SERVICE_NAME)) else: #if self.use_existing_service: # _handle_error( "connecting to existing '{}' service failed (service is not running)".format(SERVICE_NAME) ) try: win32serviceutil.StartService(SERVICE_NAME) win32serviceutil.WaitForServiceStatus( SERVICE_NAME, win32service.SERVICE_RUNNING, 1) self.driver_loaded = True if logger().DEBUG: logger().log( "[helper] service '{}' started".format(SERVICE_NAME)) except pywintypes.error as err: _handle_error( "service '{}' didn't start: {} ({:d})".format( SERVICE_NAME, err.args[2], err.args[0]), err.args[0]) self.driverpath = win32serviceutil.LocateSpecificServiceExe( SERVICE_NAME) return True
def Start(serviceName, waitSecs=30): err = 0 try: win32serviceutil.StartService(serviceName) if waitSecs: win32serviceutil.WaitForServiceStatus(serviceName, win32service.SERVICE_RUNNING, waitSecs) except win32service.error, exc: print "Error starting service: %s" % exc.strerror err = exc.winerror
def start_service(self, name): svc_name = self._make_service_name(name) try: win32serviceutil.StartService(svc_name) # TODO: what happens on timeout win32serviceutil.WaitForServiceStatus(svc_name, win32service.SERVICE_RUNNING, 5) except pywintypes.error: raise RuntimeError("can not start service '%s'" % name)
def stop_service(self, name): svc_name = self._make_service_name(name) try: win32serviceutil.StopService(svc_name) # TODO: exception on timeout win32serviceutil.WaitForServiceStatus(svc_name, win32service.SERVICE_STOPPED, 5) except pywintypes.error: pass
def EnsureServiceIsStarted(serviceName, waitSecs=30): err = 0 try: status = win32serviceutil.QueryServiceStatus(serviceName)[1] if win32service.SERVICE_RUNNING != status: if win32service.SERVICE_START_PENDING != status: win32serviceutil.StartService(serviceName) if waitSecs: win32serviceutil.WaitForServiceStatus(serviceName, win32service.SERVICE_RUNNING, waitSecs) except win32service.error, exc: err = exc.winerror
def Stop(serviceName, waitSecs=30): err = 0 try: if waitSecs: win32serviceutil.StopServiceWithDeps(serviceName, waitSecs=waitSecs) else: win32serviceutil.StopService(serviceName) if waitSecs: win32serviceutil.WaitForServiceStatus(serviceName, win32service.SERVICE_STOPPED, waitSecs) except win32service.error, exc: print "Error stopping service: %s (%d)" % (exc.strerror, exc.winerror) err = exc.winerror
def setup(cls, cmd, user=None, password=None, startup='manual', cwd=None, wait=0): from gramex.config import app_log name, service_name = cls._svc_display_name_, cls._svc_name_ port = getattr(cls, '_svc_port_', None) if cwd is None: cwd = os.getcwd() info = (name, cwd, 'port %s' % port if port is not None else '') service_class = win32serviceutil.GetServiceClassString(cls) startup = cls.startup_map[startup] running = win32service.SERVICE_RUNNING if cmd[0] == 'install': win32serviceutil.InstallService( service_class, service_name, displayName=name, description=cls._svc_description_, startType=startup, userName=user, password=password) win32serviceutil.SetServiceCustomOption(cls._svc_name_, 'cwd', cwd) app_log.info('Installed service. %s will run from %s %s' % info) elif cmd[0] in {'update', 'change'}: win32serviceutil.ChangeServiceConfig( service_class, service_name, displayName=name, description=cls._svc_description_, startType=startup, userName=user, password=password) win32serviceutil.SetServiceCustomOption(cls._svc_name_, 'cwd', cwd) app_log.info('Updated service. %s will run from %s %s' % info) elif cmd[0] in {'remove', 'uninstall'}: try: win32serviceutil.StopService(service_name) except pywintypes.error as e: if e.args[0] != winerror.ERROR_SERVICE_NOT_ACTIVE: raise win32serviceutil.RemoveService(service_name) app_log.info('Removed service. %s ran from %s %s' % info) elif cmd[0] == 'start': win32serviceutil.StartService(service_name, cmd[1:]) if wait: win32serviceutil.WaitForServiceStatus(service_name, running, wait) app_log.info('Started service %s at %s %s' % info) elif cmd[0] == 'stop': if wait: win32serviceutil.StopServiceWithDeps(service_name, waitSecs=wait) else: win32serviceutil.StopService(service_name) app_log.info('Stopped service %s at %s %s' % info) elif cmd[0]: app_log.error('Unknown command: %s' % cmd[0])
if logger().VERBOSE: logger().log("[helper] stopping service '%s'.." % SERVICE_NAME) try: win32api.CloseHandle(self.driver_handle) self.driver_handle = None win32serviceutil.StopService(SERVICE_NAME) except pywintypes.error, (hr, fn, msg): logger().error("StopService failed: %s (%d)" % (msg, hr)) return False finally: self.driver_loaded = False try: win32serviceutil.WaitForServiceStatus(SERVICE_NAME, win32service.SERVICE_STOPPED, 1) if logger().VERBOSE: logger().log("[helper] service '%s' stopped" % SERVICE_NAME) except pywintypes.error, (hr, fn, msg): logger().warn("service '%s' didn't stop: %s (%d)" % (SERVICE_NAME, msg, hr)) return False return True def get_driver_handle(self): # This is bad but DeviceIoControl fails ocasionally if new device handle is not opened every time ;( if (self.driver_handle is not None) and (INVALID_HANDLE_VALUE != self.driver_handle): return self.driver_handle
def wait_service(name: str, status: int, secs: int) -> None: win32serviceutil.WaitForServiceStatus(name, status, secs)
if (len(sys.argv) < 4) : print("[ERROR] Runtime exception: invalid number of parameters!") host_name = socket.gethostname() service_name = sys.argv[1] # If this script has not superuser, it relaunch itself with superuser permissions if not winUAC.isAdmin() : print("[LOG] Script was running without superuser permissions!") procInfo = winUAC.winSudo("python.exe", sys.argv) print("[LOG] Call info: ", procInfo) else : print("[LOG] Script was running with superuser permissions!") status = win32serviceutil.QueryServiceStatus(service_name, host_name)[1] # Check if the service is running ad stop it if (status == win32service.SERVICE_RUNNING) : win32serviceutil.StopService(service_name, host_name) print("Services" + service_name + " was stopped...") win32serviceutil.WaitForServiceStatus(service_name, win32service.SERVICE_RUNNING) # Copy all file of interests for file in sys.argv[3:]: src_path, file_name = os.path.split(file) fileUtils.copy(file, sys.argv[2] + "\\" + file_name, True) # Restart service win32serviceutil.StartService(service_name, None, host_name) print("Services" + service_name + " was restarted...")
if not util.has_admin_rights(): print "You must be an administrator/root to stop bam2." sys.exit(0) print "stopping bam2" if util.get_platform() == "Windows": import win32serviceutil, win32service sc_path = os.getenv("SYSTEMROOT", "") + os.sep + "System32" + os.sep + "sc" service_name = "bigsql.bam2" cmd = sc_path + ' stop ' + service_name process_output = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate() print process_output[0] try: win32serviceutil.WaitForServiceStatus(service_name, win32service.SERVICE_STOPPED, 10) except win32service.error as exc: print("Error stopping service: %s" % exc.strerror) err = exc.winerror sys.exit(1) elif util.get_platform() == "Darwin": launctl_load_cmd = "launchctl stop bigsql.bam2" os.system(launctl_load_cmd) else: subprocess.Popen("pkill -f " + homedir + os.sep + "bin" + os.sep + "start_crossbar.py", shell=True)
def service_stop(service_name): win32serviceutil.StopService(service_name) win32api.Sleep(2000) return win32serviceutil.WaitForServiceStatus(service_name, win32service.SERVICE_STOPPED, waitSecs=4)
def service_start(service_name): """Start a service by its service name""" win32serviceutil.StartService(service_name) return win32serviceutil.WaitForServiceStatus(service_name, win32service.SERVICE_RUNNING, waitSecs=4)