コード例 #1
0
ファイル: port.py プロジェクト: hilbernate/wpi
    def save(self):
        for k, v in self.data.items():
            for one in self._tcpipobjs_to_del:
                one.Delete_()

            if isinstance(v, TCPIPPort):
                win32obj = self._tcpipobjs[k]
                win32obj.Name = k
                v.save_to(win32obj)
                win32obj.Put_()

            elif isinstance(v, LocalPort):
                self._localregtips[k] = v.value or ''

        if self._localregtips != self._old_localregtips:
            self._localregtips.save_to(_LOCAL_PORT_REG_KEY)
            self._old_localregtips = copy.deepcopy(self._localregtips)

            logging.info('restart print spooler')
            _ = 'Print Spooler'
            win32serviceutil.RestartService('Print Spooler')
            sec = 0
            while win32serviceutil.QueryServiceStatus(_)[1] != 4 and sec < 10:
                time.sleep(0.2)
                sec += 0.2

            print(sec)
コード例 #2
0
ファイル: win32.py プロジェクト: MIT-LCP/mitre_deid_toolkit
def signal_child(service, command):
    if command == 'stop':
        win32serviceutil.StopService(service)
    elif command == 'restart':
        win32serviceutil.RestartService(service)
    else:
        win32serviceutil.ControlService(service, control_codes[command])
コード例 #3
0
 def service_info(self, action, machine, service):
     #Interacts with the Window's service controller
     #The netconnection must be completed first
     #If netconnection is not done first, a Permission denied may return from SC controller
     if action == 'stop':
         win32serviceutil.StopService(service, machine)
         print '%s stopped successfully' % service
     elif action == 'start':
         win32serviceutil.StartService(service, None, machine)
         print '%s started successfully' % service
     elif action == 'restart':
         win32serviceutil.RestartService(service, machine)
         print '%s restarted successfully' % service
     elif action == 'status':
         #print win32serviceutil.QueryServiceStatus(service, machine)
         retStatus = win32serviceutil.QueryServiceStatus(service,
                                                         machine)[1]
         if retStatus == self.RUNNING:  # scvType, svcState, svcControls, err, svcErr, svcCP, svcWH
             print "%s on %s is running" % (service, machine)
             return self.RUNNING
         elif retStatus == self.STARTING:
             print '%s on %s is STARTING' % (service, machine)
             return self.STARTING
         elif retStatus == self.STOPPING:
             print '%s on %s is STOPPING' % (service, machine)
             return self.STOPPING
         elif retStatus == self.STOPPED:
             print '%s on %s is STOPPED***************' % (service, machine)
             return self.STOPPED
         else:
             print "Failed to get status for %s on %s" % (service, machine)
コード例 #4
0
def function_witn_warning():
    root = tkinter.Tk()
    root.withdraw()
    #ошибка 5 - ошибка доступа, нужно запускать с правами админа
    win32serviceutil.RestartService('postgresql-11')
    messagebox.showinfo(
        "Alert",
        "We're gonna reload your PostgreSQL server, please don't be alarmed")
コード例 #5
0
 def restart():
     print("restarting")
     if settings["Process_Listen"] is None:
         print("no process to restart")
         return
     #print("win32serviceutil.RestartService({})".format(settings["Process_Listen"]))
     win32serviceutil.RestartService(
         settings["Process_Listen"].rstrip(".exe"))
コード例 #6
0
ファイル: winadddns.py プロジェクト: esabouraud/scripts
def reconfigureUnboundService(unboundconfnewlines):
    unboundconf = open("unboundservice.conf.tmpl").read()
    unboundconf += unboundconfnewlines
    logging.debug(unboundconf)
    open(getUnboundConfPath(), "w").write(unboundconf)

    logging.info("Restart Unbound service.")
    win32serviceutil.RestartService('unbound')
コード例 #7
0
def restart1cService(self):
    logging.info('restart')
    try:
        win32serviceutil.RestartService(
            'Агент сервера 1С:Предприятия 8.3 (x86-64)',
            machine=self.Srvr)
    except Exception as err:
        logging.error(f'{err}')
コード例 #8
0
ファイル: test_cabsagent.py プロジェクト: jeason-j/cabs
 def restart():
     logging.info("restarting")
     if settings["Process_Listen"] is None:
         logging.warning("no process to restart")
         return
     #print "win32serviceutil.RestartService({})".format(settings["Process_Listen"])
     win32serviceutil.RestartService(
         settings["Process_Listen"].rstrip(".exe"))
コード例 #9
0
def reset():
    try:
        #subprocess.Popen(endereco_reset)
        win32serviceutil.RestartService(service, machine)
        flash("Sucesso Reset!")
    except:
        flash("falha Reset!")
        print('A execucao do serviço falhou!')
    return redirect(url_for('home'))
コード例 #10
0
ファイル: gui.py プロジェクト: jyogi/purvar-agent
def service_manager(action):
    try:
        if action == 'stop':
            win32serviceutil.StopService(DATADOG_SERVICE)
        elif action == 'start':
            win32serviceutil.StartService(DATADOG_SERVICE)
        elif action == 'restart':
            win32serviceutil.RestartService(DATADOG_SERVICE)
    except Exception as e:
        warning_popup("Couldn't %s service: \n %s" % (action, str(e)))
コード例 #11
0
def service_do_action(service, action):
    if action == 'stop':
        win32serviceutil.StopService(service)
        print('{} is stopping'.format(service))
    elif action == 'start':
        win32serviceutil.StartService(service)
        print('{} is starting'.format(service))
    elif action == 'restart':
        win32serviceutil.RestartService(service)
        print('{} is restarting'.format(service))
    else:
        return "unknown command"
コード例 #12
0
ファイル: watchdog.py プロジェクト: zjorundur/eve-metrics
def RestartService(svc, retry=0):
    print "Restarting service %s..." % svc
    try:
        win32serviceutil.RestartService(svc)
    except:
        print "Exception trying to restart service: %s" % traceback.format_exc(
        )
        if not retry:
            print "Retrying..."
            RestartService(svc, 1)
        else:
            raise
    print "Done restarting service"
コード例 #13
0
def restart_service(service_name='TermService'):
    current_uuid = uuid.uuid4().get_hex()
    print("INFO: RESTARTING SERVICE\'{service}\'".format(service=service_name) + current_uuid)
    send_message("INFO: RESTARTING SERVICE\'{service}\'".format(service=service_name),
                 "RESTARTING SERVICE.\n\n-------------------\n\n>ID: " + current_uuid)
    status = win32serviceutil.QueryServiceStatus(service_name)[1]
    if status == RUNNING:
        try:
            win32serviceutil.RestartService(service_name)
        except Exception as e:
            print 'Access denied or service not exist.'
            if isinstance(e.args, Iterable):
                for arg in e.args:
                    print decoding(arg),
            sys.exit(1)

        time.sleep(2)
        status = win32serviceutil.QueryServiceStatus(service_name)[1]
        if status == RUNNING:
            print("SUCCESS: SERVICE \'{service}\' RESTARTED".format(service=service_name) + current_uuid)
            send_message("SUCCESS: SERVICE \'{service}\' RESTARTED".format(service=service_name),
                         "SERVICE RESTARTED.\n\n-------------------\n\n>ID: " + current_uuid)
            return True
        else:
            # blocking until service started
            running_flag = True
            try_times = 0
            sleep_seconds = 2
            waiting_time = 300
            while running_flag:
                print "waiting for service {service} restart.".format(service=service_name)
                status_code = win32serviceutil.QueryServiceStatus(service_name)[1]
                if status_code == RUNNING:
                    running_flag = False
                time.sleep(sleep_seconds)
                try_times += 1
                if try_times > waiting_time / sleep_seconds:
                    print("FAILED: SERVICE  \'{service}\' CAN NOT START".format(service=service_name) + current_uuid)
                    send_message("FAILED: SERVICE  \'{service}\' CAN NOT START".format(service=service_name),
                                 "CAN NOT START SERVICE, TIMEOUT\n\n-------------------\n\n>ID: " + current_uuid)
                    sys.exit(1)

            print("SUCCESS: SERVICE \'{service}\' RESTARTED".format(service=service_name) + current_uuid)
            send_message("SUCCESS: SERVICE \'{service}\' RESTARTED".format(service=service_name),
                         "SERVICE RESTARTED.\n\n-------------------\n\n>ID: " + current_uuid)
            return True
    else:
        print message_status_map[status], " And this is unusual."
        print("WARNING: UNUSUAL SERVICE \'{service}\' STATE".format(service=service_name) + current_uuid)
        send_message("WARNING: UNUSUAL SERVICE \'{service}\' STATE".format(service=service_name),
                     "SERVICE STATE IS UNUSUAL.\n\n-------------------\n\n>ID: " + current_uuid)
コード例 #14
0
 def restart(self):
     if self.running:
         win32serviceutil.RestartService(self.service)
         time.sleep(2)
         if self.running:
             if self.verbose:
                 print(f"[+] {self.service} restarted successfully.")
             return True
         else:
             if self.verbose:
                 print(f"[-] Cannot start {self.service}")
             return False
     elif self.verbose:
         print(f"[!] {self.service} is not running.")
コード例 #15
0
def service_info(action, machine, service):
    running = service_running(service, machine)
    servnam = f'service {service} on machine {machine}'
    action = action.lower()

    if action == 'stop':
        if not running:
            inactive.append(service)
            print(f"Can't stop, {servnam} not running")
            return 0
        win32serviceutil.StopService(service, machine)
        if running:
            print(f"Can't stop {servnam} (???)")
            active.append(service)
            return 0
        print(f'{servnam} stopped successfully')
        inactive.append(service)

    elif action == 'start':
        if running:
            print(f"Can't start, {servnam} already running")
            active.append(service)
            return 0
        win32serviceutil.StartService(service, machine)
        if not running:
            print(f"Can't start {servnam} (???)")
            inactive.append(service)
            return 0
        print(f'{servnam} started successfully')
        active.append(service)

    elif action == 'restart':
        if not running:
            inactive.append(service)
            return 0
        win32serviceutil.RestartService(service, machine)
        if not running:
            inactive.append(service)
            print(f"Can't restart {servnam} (???)")
            return 0
        active.append(service)
        print(f'{servnam} restarted successfully')

    elif action == 'status':
        if not running:
            inactive.append(service)
        else:
            active.append(service)
    else:
        return 0
コード例 #16
0
 def restart(self):
     if self.running:
         win32serviceutil.RestartService(self.service)
         time.sleep(2)
         if self.running:
             if self.verbose:
                 pprint(f"{self.service} restarted successfully.",
                        headers.SCS)
             return True
         else:
             if self.verbose:
                 pprint(f"Cannot start {self.service}", headers.ERR)
             return False
     elif self.verbose:
         pprint(f"{self.service} is not running.", headers.WRN)
コード例 #17
0
def service_info(action, machine, target):
    if action == 'stop': 
        win32serviceutil.StopService(target, machine)
        print('%s stopped successfully' % service)
    elif action == 'start': 
        win32serviceutil.StartService(target, machine)
        print('%s started successfully' % service)
    elif action == 'restart': 
        win32serviceutil.RestartService(target, machine)
        print('%s restarted successfully' % service)
    elif action == 'status':
        if win32serviceutil.QueryServiceStatus(target, machine)[1] == 4:
            print("%s is running normally" % target )
        else:
            print("%s is *not* running" % target)
コード例 #18
0
def ServiceManager(action, machine, service):
    if action == 'stop':
        win32serviceutil.StopService(service, machine)
    elif action == 'start':
        win32serviceutil.StartService(service, machine)
    elif action == 'restart':
        win32serviceutil.RestartService(service, machine)
    elif action == 'status':
        srvStatus = win32serviceutil.QueryServiceStatus(service, machine)[1]
        print 'Service Status:', srvStatus
        if srvStatus == 4:
            srvStatus = "%s running normally" % service
        elif srvStatus == 1:
            srvStatus = "%s is *not* running" % service
        else:
            srvStatus = 'NONE'
        print 'ServiceManager: %s' % srvStatus
        return srvStatus
コード例 #19
0
def service_info(action, machine, service):
    if action == 'stop': 
        win32serviceutil.StopService(service, machine)
        print '%s stopped successfully' % service
        time.sleep(3)
    elif action == 'start': 
        win32serviceutil.StartService(service, machine)
        print '%s started successfully' % service
        time.sleep(3)
    elif action == 'restart': 
        win32serviceutil.RestartService(service, machine)
        print '%s restarted successfully' % service
        time.sleep(3)
    elif action == 'status':
        if win32serviceutil.QueryServiceStatus(service, machine)[1] == 4:
            print "%s is running normally" % service 
        else:
            print "%s is *not* running" % service
コード例 #20
0
ファイル: instance.py プロジェクト: datakurre/plonectl
        def do_restart(self, arg):

            if not shell.IsUserAnAdmin():
                print(ERR_MSG_NOT_ADMIN)
                return

            status = self._get_service_status()
            if status is None:
                print('ERROR: Zope is not installed as Windows service.')
                return
            elif status == win32service.SERVICE_STOPPED:
                print('ERROR: The Zope Windows service has not been started.')
                return
            name = self._get_service_name()
            try:
                win32serviceutil.RestartService(name)
                print('Restarting Windows Service "{}".'.format(name))
            except pywintypes.error:
                traceback.print_exc()
コード例 #21
0
def service_control(service, action):
    try:
        if action == 'stop':
            win32serviceutil.StopService(service)
            return EnumStatusService.getStatus(
                win32serviceutil.QueryServiceStatus(service)[1])
        elif action == 'start':
            win32serviceutil.StartService(service)
            return EnumStatusService.getStatus(
                win32serviceutil.QueryServiceStatus(service)[1])
        elif action == 'restart':
            win32serviceutil.RestartService(service)
            return EnumStatusService.getStatus(
                win32serviceutil.QueryServiceStatus(service)[1])
        elif action == 'status':
            return EnumStatusService.getStatus(
                win32serviceutil.QueryServiceStatus(service)[1])
    except:
        return 'failed'
コード例 #22
0
def services(action, serviceName):
    try:
        if action == 'start':
            win32serviceutil.StartService(serviceName)
        elif action == 'stop':
            win32serviceutil.StopService(serviceName)
        elif action == 'restart':
            win32serviceutil.RestartService(serviceName)
        elif action == 'status':
            try:
                if win32serviceutil.QueryServiceStatus(serviceName)[1] == 4:
                    return "Running"
                else:
                    return "Not running"
            except:
                return "Not exists"
    except Exception as e:
        messagebox.showerror("Error", e)

    root.after(2000, printServices)
コード例 #23
0
def service_info(action, service):

    if action == 'stop':
        win32serviceutil.StopService(service)
        log.info(
            'service={0} action=stopped result=successfully'.format(service))
    elif action == 'start':
        win32serviceutil.StartService(service)
        log.info(
            'service={0} action=started result=successfully'.format(service))
    elif action == 'restart':
        win32serviceutil.RestartService(service)
        long.info(
            'service={0} action=restarted result=successfully'.format(service))
    elif action == 'status':
        if win32serviceutil.QueryServiceStatus(service)[1] == 4:
            log.info('service={0} status=running'.format(service))
            return 'running'
        else:
            log.info('service={0} status="*not* running"'.format(service))
            return 'notrunning'
def restart_service():
    """Restart program and return its PID"""

    global service_is_running
    service_is_running = False

    # Check that the service is running before stopping it
    for process in wmi.WMI().Win32_Process():
        if process.Name == processName:
            print("[*] Stopping the service...")
            # Forcefully terminate the process
            subprocess.Popen('taskkill /f /im ' + processName).communicate()

    print("[*] Starting the service...")
    time.sleep(timeToRestartService)  # let enough time for the service to stop
    running = service_running(service, machine)
    if not running:
        win32serviceutil.StartService(service, machine)
        #subprocess.Popen(executable)
    else:
        win32serviceutil.RestartService(service, machine)

    pid = is_service_started()
    if pid:
        print("[*] The service was restarted.")
    else:
        print("[-] Service was not found in process list. Restarting...")
        return restart_service()

    if is_service_responsive():
        print("[*] Service responds to TCP requests. Green ligth.")
        service_is_running = True
        return pid
    else:
        print("[-] Service does not respond to TCP requests. Restarting...")
        return restart_service()
コード例 #25
0
 def reload(self):
     """Reload the windows service
     """
     win32serviceutil.RestartService(self.service_name)
コード例 #26
0
def RestartWindowsService():
    serviceName = "POS_SAPB1_Schedule"
    win32serviceutil.RestartService(serviceName)
コード例 #27
0
        epilog="Then restart service")
    parser.add_argument('host',
                        metavar='HOST',
                        help='New synergy server IP address')
    args = parser.parse_args()

    try:
        socket.inet_aton(args.host)
    except socket.error:
        sys.stderr.write('%s is not a valid host\n' % args.host)
        sys.exit(-1)

    hostregkey = _winreg.OpenKey(
        _winreg.HKEY_CURRENT_USER, 'Software\\Synergy\\Synergy', 0,
        _winreg.KEY_READ | _winreg.KEY_QUERY_VALUE | _winreg.KEY_SET_VALUE)
    oldhost, type = _winreg.QueryValueEx(hostregkey, 'serverHostname')
    print 'Change synergy server from %s to %s' % (oldhost, args.host)
    _winreg.SetValueEx(hostregkey, 'serverHostname', 0, type, args.host)
    _winreg.FlushKey(hostregkey)

    cmdregkey = _winreg.OpenKey(
        _winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Synergy', 0,
        _winreg.KEY_WOW64_64KEY | _winreg.KEY_READ | _winreg.KEY_QUERY_VALUE
        | _winreg.KEY_SET_VALUE)
    oldcmd, type = _winreg.QueryValueEx(cmdregkey, 'Command')
    _winreg.SetValueEx(cmdregkey, 'Command', 0, type,
                       oldcmd.replace(oldhost, args.host))
    _winreg.FlushKey(cmdregkey)

    win32serviceutil.RestartService('Synergy')
コード例 #28
0
 def restart(cls):
     win32serviceutil.RestartService(cls._svc_name_)
コード例 #29
0
def restart():
    service = LoggerWindowsService._svc_name_
    logging.info('==> Restarting service[%s]' % service)
    win32serviceutil.RestartService(service)
コード例 #30
0
def start_tpp_services(f):
    f.write("starting tpp services...\n")
    log_service = "VenafiLogServer"
    tpp_service = "VED"
    win32serviceutil.RestartService(tpp_service)
    win32serviceutil.RestartService(log_service)