Exemplo n.º 1
0
    def test_win_service_get(self):
        name = next(psutil.win_service_iter()).name()

        with self.assertRaises(psutil.NoSuchProcess) as cm:
            psutil.win_service_get(name + '???')
        self.assertEqual(cm.exception.name, name + '???')

        # test NoSuchProcess
        service = psutil.win_service_get(name)
        exc = WindowsError(
            psutil._psplatform.cext.ERROR_SERVICE_DOES_NOT_EXIST, "")
        with mock.patch("psutil._psplatform.cext.winservice_query_status",
                        side_effect=exc):
            self.assertRaises(psutil.NoSuchProcess, service.status)
        with mock.patch("psutil._psplatform.cext.winservice_query_config",
                        side_effect=exc):
            self.assertRaises(psutil.NoSuchProcess, service.username)

        # test AccessDenied
        exc = WindowsError(
            psutil._psplatform.cext.ERROR_ACCESS_DENIED, "")
        with mock.patch("psutil._psplatform.cext.winservice_query_status",
                        side_effect=exc):
            self.assertRaises(psutil.AccessDenied, service.status)
        with mock.patch("psutil._psplatform.cext.winservice_query_config",
                        side_effect=exc):
            self.assertRaises(psutil.AccessDenied, service.username)

        # test __str__ and __repr__
        self.assertIn(service.name(), str(service))
        self.assertIn(service.display_name(), str(service))
        self.assertIn(service.name(), repr(service))
        self.assertIn(service.display_name(), repr(service))
Exemplo n.º 2
0
    def test_win_service_get(self):
        name = next(psutil.win_service_iter()).name()

        with self.assertRaises(psutil.NoSuchProcess) as cm:
            psutil.win_service_get(name + '???')
        self.assertEqual(cm.exception.name, name + '???')

        # test NoSuchProcess
        service = psutil.win_service_get(name)
        exc = WindowsError(
            psutil._psplatform.cext.ERROR_SERVICE_DOES_NOT_EXIST, "")
        with mock.patch("psutil._psplatform.cext.winservice_query_status",
                        side_effect=exc):
            self.assertRaises(psutil.NoSuchProcess, service.status)
        with mock.patch("psutil._psplatform.cext.winservice_query_config",
                        side_effect=exc):
            self.assertRaises(psutil.NoSuchProcess, service.username)

        # test AccessDenied
        exc = WindowsError(psutil._psplatform.cext.ERROR_ACCESS_DENIED, "")
        with mock.patch("psutil._psplatform.cext.winservice_query_status",
                        side_effect=exc):
            self.assertRaises(psutil.AccessDenied, service.status)
        with mock.patch("psutil._psplatform.cext.winservice_query_config",
                        side_effect=exc):
            self.assertRaises(psutil.AccessDenied, service.username)

        # test __str__ and __repr__
        self.assertIn(service.name(), str(service))
        self.assertIn(service.display_name(), str(service))
        self.assertIn(service.name(), repr(service))
        self.assertIn(service.display_name(), repr(service))
Exemplo n.º 3
0
    def validate_services(self, to_validate):
        after_validation = []
        for potential in to_validate:
            if potential != '':
                try:
                    psutil.win_service_get(potential)
                    after_validation.append(potential)
                except psutil._exceptions.NoSuchProcess:
                    log.warning(
                        'While validating: {}: No such service found: {}, check your spelling in config.'
                        .format(to_validate, potential))

        return after_validation
Exemplo n.º 4
0
    def __init__(self):
        self.watchdog = WatchDog()
        self.config = ConfigReader()
        self.watch_services = self.config.watch_services
        self.restart_services = self.config.restart_services
        self.combined_services = [
            psutil.win_service_get(x)
            for x in set(self.watch_services + self.restart_services)
        ]
        self.hard_restart = self.config.hard_restart

        self.restart_after = self.config.restart_after
        self.time_delay = self.config.time_delay

        self.start_wait = 0.1
        self.stop_wait = 0.1
        self.force_stop_wait = 0.1
        self.start_max_attempts = self.config.start_attempts
        self.start_attempt_counter = 0

        log.info('NOW GUARDING: \n'
                 'List of services to watch: {}\n'
                 'List of services to restart every {} minutes: {}\n'
                 'and those of them should be killed on stopping: {}'.format(
                     self.watch_services, self.time_delay,
                     self.restart_services, self.hard_restart))
Exemplo n.º 5
0
def get_service(name):
    service = None
    try:
        service = psutil.win_service_get(name)
        service = service.as_dict()
        if service:
            print("Service found: ", service)
        else:
            print("Service not found")

        if service and service['status'] == 'running':
            print("Service is running")
            os.chdir("C:/ZettaBrasil/ZettaNFCe")                             
            os.startfile("ZettaNFCe.exe")
        else: 
            print("Service is not running")
            print("Starting server")
            servico.StartService("PostgreSQL_10_Zetta")
            time.sleep(10)
            print("Done")
            os.chdir("C:/ZettaBrasil/ZettaNFCe")                             
            os.startfile("ZettaNFCe.exe")                      
            time.sleep(10)
            
    

    except Exception as ex:
        # raise psutil.NoSuchProcess if no service with such name exists
        print(str(ex))
Exemplo n.º 6
0
    def un_install_package(self):
        # once we modify it, the uninstaller will leave it there...
        if self.get_arangod_conf().exists():
            self.get_arangod_conf().unlink()
        uninstaller = "Uninstall.exe"
        tmp_uninstaller = Path("c:/tmp") / uninstaller
        uninstaller = self.cfg.installPrefix / uninstaller

        if uninstaller.exists():
            # copy out the uninstaller as the windows facility would do:
            shutil.copyfile(uninstaller, tmp_uninstaller)

            cmd = [tmp_uninstaller,
                   '/PURGE_DB=1',
                   '/S',
                   '_?=' + str(PureWindowsPath(self.cfg.installPrefix))]
            logging.info('running windows package uninstaller')
            logging.info(str(cmd))
            uninstall = psutil.Popen(cmd)
            uninstall.wait()
        if self.cfg.log_dir.exists():
            shutil.rmtree(self.cfg.log_dir)
        if tmp_uninstaller.exists():
            tmp_uninstaller.unlink()
        # the smaller the wintendo, the longer we shal let it rest,
        # since it needs to look at all these files we
        # just unloaded into it to make sure no harm originates from them.
        time.sleep(30 / multiprocessing.cpu_count())
        try:
            logging.info(psutil.win_service_get('ArangoDB'))
            self.get_service()
            if self.service and self.service.status() != 'stopped':
                logging.info("service shouldn't exist anymore!")
        except:
            pass
Exemplo n.º 7
0
    def fix_mesh(self):
        """
        Mesh agent will randomly bug out and kill cpu usage
        This functions runs every hour as a scheduled task to solve that
        """
        mesh = [
            proc.info
            for proc in psutil.process_iter(attrs=["pid", "name"])
            if "meshagent" in proc.info["name"].lower()
        ]

        if mesh:
            try:
                proc = psutil.Process(mesh[0]["pid"])
            except psutil.NoSuchProcess:
                try:
                    self._mesh_service_action("stop")
                    sleep(3)
                    self._mesh_service_action("start")
                finally:
                    return

            cpu_usage = proc.cpu_percent(10) / psutil.cpu_count()

            if cpu_usage >= 18.0:
                self.logger.warning(
                    f"Mesh agent cpu usage: {cpu_usage}%. Restarting..."
                )
                self._mesh_service_action("stop")

                attempts = 0
                while 1:
                    svc = psutil.win_service_get("mesh agent")
                    if svc.status() != "stopped":
                        attempts += 1
                        sleep(1)
                    else:
                        attempts = 0

                    if attempts == 0 or attempts >= 30:
                        break

                # sometimes stopping service doesn't kill the hung proc
                mesh2 = [
                    proc.info
                    for proc in psutil.process_iter(attrs=["pid", "name"])
                    if "meshagent" in proc.info["name"].lower()
                ]

                if mesh2:
                    pids = []
                    for proc in mesh2:
                        pids.append(proc["pid"])

                    for pid in pids:
                        kill_proc(pid)

                    sleep(1)

                self._mesh_service_action("start")
Exemplo n.º 8
0
def _get_service_by_name(name):
    service = None
    try:
        service = psutil.win_service_get(name)
    except:
        pass
    return service
Exemplo n.º 9
0
def update_version():
    #检测是否有安装服务
    if check_install():
        logger.info("local_agent_version is installed")
        #检测跟服务器的版本是否一致
        if get_agent_version() == get_local_version():
            logger.info("The Version is same")
        else:
            path = psutil.win_service_get("AgentService").binpath()
            logger.info("try stop local_agent_version")
            os.popen(path + " stop")
            time.sleep(5)
            os.popen(path + " remove")
    else:
        r = requests.get("http://{0}/static/dist/update/{1}.exe".format(
            server_ip, get_agent_version()))
        with open("%s.exe" % get_agent_version(), 'wb') as code:
            code.write(r.content)
        code.close()
        time.sleep(5)
        this_file = inspect.getfile(inspect.currentframe())
        dirpath = os.path.abspath(os.path.dirname(this_file))
        os.popen("{0}\\{1}.exe install".format(dirpath, get_agent_version()))
        time.sleep(5)
        os.popen("{0}\\{1}.exe start".format(dirpath, get_agent_version()))
Exemplo n.º 10
0
 def getService(self, service):
     try:
         serv = psutil.win_service_get(service)
     except (psutil.NoSuchProcess):
         self.logger.writeEntry('Could not find ' + service + ' process')
         return False
     return serv
Exemplo n.º 11
0
 def install_package(self):
     cmd = [str(self.cfg.package_dir / self.server_package),
            '/PASSWORD='******'/INSTDIR=' + str(PureWindowsPath(self.cfg.installPrefix)),
            '/DATABASEDIR=' + str(PureWindowsPath(self.cfg.dbdir)),
            '/APPDIR=' + str(PureWindowsPath(self.cfg.appdir)),
            '/PATH=0',
            '/S',
            '/INSTALL_SCOPE_ALL=1']
     logging.info('running windows package installer:')
     logging.info(str(cmd))
     install = psutil.Popen(cmd)
     install.wait()
     self.service = psutil.win_service_get('ArangoDB')
     while not self.check_service_up():
         logging.info('starting...')
         time.sleep(1)
     self.enable_logging()
     self.stop_service()
     # the smaller the wintendo, the longer we shal let it rest,
     # since it needs to look at all these files we
     # just unloaded into it to make sure no harm originates from them.
     time.sleep(60 / multiprocessing.cpu_count())
     self.set_system_instance()
     self.start_service()
     logging.info('Installation successfull')
Exemplo n.º 12
0
def getServiceStatus(serviceName):
    try:
        service = psutil.win_service_get(serviceName).as_dict()
    except:
        return 'Not Installed'

    return service
Exemplo n.º 13
0
 def getWindowsServices(self):
     print("Begin Collecting Started Windows Services ... ")
     serviceArray = psutil.win_service_iter()
     for service in serviceArray:
         try:
             serviceDetails = psutil.win_service_get(service._name)
             serviceDict = serviceDetails.as_dict()
             if (serviceDict["status"] == "running"):
                 service = {}
                 if (serviceDict["display_name"] != None):
                     service["name"] = serviceDict["display_name"]
                 if (serviceDict["username"] != None):
                     service["user"] = serviceDict["username"]
                 if (serviceDict["pid"] != None):
                     service["pid"] = serviceDict["pid"]
                 service["status"] = serviceDict["status"]
                 reportJSON["machineInfo"]["services"]["active"].append(
                     service)
             if (serviceDict["status"] == "stopped"):
                 service = {}
                 if (serviceDict["display_name"] != None):
                     service["name"] = serviceDict["display_name"]
                 if (serviceDict["username"] != None):
                     service["user"] = serviceDict["username"]
                 service["status"] = serviceDict["status"]
                 reportJSON["machineInfo"]["services"]["inactive"].append(
                     service)
         except:
             print("Could Not Record Windows Services ... Moving On ... ")
     print("Successfully Recorded Windows Services!")
Exemplo n.º 14
0
def getService(name):
	for i in name
		service = None
		try:
		service = psutil.win_service_get(i)
		service = service.as_dict()
		except Exception as ex:
Exemplo n.º 15
0
 def processinfo(self, processName):
     try:
         service = psutil.win_service_get(processName)
         return service.as_dict()['pid']
     except psutil.NoSuchProcess as e:
         logger.info('没有找到服务名为:%s 的进程PID' % processName)
         return None
Exemplo n.º 16
0
 def query(self, name):
     """ Returns service information as dict """
     try:
         info = psutil.win_service_get(name)
     except psutil.NoSuchProcess:
         return False
     else:
         return (info.as_dict())
Exemplo n.º 17
0
def getService(name): 
        service = None
        try:
            service = psutil.win_service_get(name)
            service = service.as_dict()
        except Exception as ex:
            print(str(ex))
        return service
Exemplo n.º 18
0
def get_local_version():
    #获取本机服务的版本
    if check_install():
        local_version = psutil.win_service_get("AgentService").description()
        logger.info("The Local_version is %s" % local_version)
        return local_version
    else:
        return ""
Exemplo n.º 19
0
def protoandport():
    protport = {}
    if sys.platform.startswith('win'):
        for process in psutil.process_iter():
            if 'tvnserver.exe' in process.name():
                process_handler = psutil.Process(process.pid)
                for cux in process_handler.connections():
                    if cux.status == psutil.CONN_LISTEN:
                        protport['vnc'] = cux.laddr.port
            elif 'sshd.exe' in process.name():
                process_handler = psutil.Process(process.pid)
                for cux in process_handler.connections():
                    if cux.status == psutil.CONN_LISTEN:
                        protport['ssh'] = cux.laddr.port
        for service in psutil.win_service_iter():
            if 'TermService' in service.name():
                service_handler = psutil.win_service_get('TermService')
                if service_handler.status() == 'running':
                    pid = service_handler.pid()
                    process_handler = psutil.Process(pid)
                    for cux in process_handler.connections():
                        if cux.status == psutil.CONN_LISTEN:
                            protport['rdp'] = cux.laddr.port

    elif sys.platform.startswith('linux'):
        for process in psutil.process_iter():
            if 'Xvnc' in process.name():
                process_handler = psutil.Process(process.pid)
                for cux in process_handler.connections():
                    try:
                        ip = cux.laddr[0]
                        port = cux.laddr[1]
                    except Exception:
                        ip = cux.laddr.ip
                        port = cux.laddr.port
                    if cux.status == psutil.CONN_LISTEN and ip == "0.0.0.0":
                        protport['vnc'] = port
            elif 'sshd' in process.name():
                process_handler = psutil.Process(process.pid)
                for cux in process_handler.connections():
                    try:
                        ip = cux.laddr[0]
                        port = cux.laddr[1]
                    except Exception:
                        ip = cux.laddr.ip
                        port = cux.laddr.port
                    if cux.status == psutil.CONN_LISTEN and ip == "0.0.0.0":
                        protport['ssh'] = port

    elif sys.platform.startswith('darwin'):
        for process in psutil.process_iter():
            if 'ARDAgent' in process.name():
                protport['vnc'] = '5900'
        for cux in psutil.net_connections():
            if cux.laddr.port == 22 and cux.status == psutil.CONN_LISTEN:
                protport['ssh'] = '22'

    return protport
Exemplo n.º 20
0
def protoandport():
    protport = {}
    if sys.platform.startswith('win'):
        for process in psutil.process_iter():
            if 'tvnserver.exe' in process.name():
                process_handler = psutil.Process(process.pid)
                for cux in process_handler.connections():
                    if cux.status == psutil.CONN_LISTEN:
                        protport['vnc'] = cux.laddr.port
            elif 'sshd.exe' in process.name():
                process_handler = psutil.Process(process.pid)
                for cux in process_handler.connections():
                    if cux.status == psutil.CONN_LISTEN:
                        protport['ssh'] = cux.laddr.port
        for service in psutil.win_service_iter():
            if 'TermService' in service.name():
                service_handler = psutil.win_service_get('TermService')
                if service_handler.status() == 'running':
                    pid = service_handler.pid()
                    process_handler = psutil.Process(pid)
                    for cux in process_handler.connections():
                        if cux.status == psutil.CONN_LISTEN:
                            protport['rdp'] = cux.laddr.port

    elif sys.platform.startswith('linux'):
        for process in psutil.process_iter():
            if 'Xvnc' in process.name():
                process_handler = psutil.Process(process.pid)
                for cux in process_handler.connections():
                    try:
                        ip = cux.laddr[0]
                        port = cux.laddr[1]
                    except Exception:
                        ip = cux.laddr.ip
                        port = cux.laddr.port
                    if cux.status == psutil.CONN_LISTEN and ip == "0.0.0.0":
                        protport['vnc'] = port
            elif 'sshd' in process.name():
                process_handler = psutil.Process(process.pid)
                for cux in process_handler.connections():
                    try:
                        ip = cux.laddr[0]
                        port = cux.laddr[1]
                    except Exception:
                        ip = cux.laddr.ip
                        port = cux.laddr.port
                    if cux.status == psutil.CONN_LISTEN and ip == "0.0.0.0":
                        protport['ssh'] = port

    elif sys.platform.startswith('darwin'):
        for process in psutil.process_iter():
            if 'ARDAgent' in process.name():
                protport['vnc'] = '5900'
        for cux in psutil.net_connections():
            if cux.laddr.port == 22 and cux.status == psutil.CONN_LISTEN:
                protport['ssh'] = '22'

    return protport
Exemplo n.º 21
0
 def get_service(self):
     """ get a service handle """
     if self.service:
         return
     try:
         self.service = psutil.win_service_get('ArangoDB')
     except Exception as exc:
         logging.error("failed to get service! - %s", str(exc))
         return
Exemplo n.º 22
0
def getService(name):
        service = None
        try:
            service = psutil.win_service_get(name)
            service = service.as_dict()
        except Exception as ex:
            print("Something went wrong. Please contact the developer.")
            print(str(ex))
        return service
Exemplo n.º 23
0
def checkServiceStatus(server):
    status = None
    try:
        service = psutil.win_service_get(server)
        status = service.as_dict()
    except Exception as ex:
        print(str(ex))

    return status
Exemplo n.º 24
0
def services_info(log_file_path):
    '''
    ~ wmic service where started=true get name, displayname, processid, startmode, startname, pathname
    **FR**
    Liste les services démarrés sur l'ordinateur
    Retourne le dictionnaire des noms des services démarrés
    **EN**
    List computer started services
    Return the running services names dict
    '''
    writer.writer('Getting running services')
    # 1 - Ecriture début de log
    log_file = log_file_path + 'FINAL.html'
    writer.writelog(log_file, '<div><br>\n')
    elem = '<h2>Running services on computer "' + COMPUTERNAME + '"</h2>'
    writer.prepa_log_scan(log_file, elem)

    # 2 - Obtenir la liste des services démarrés
    if detect_os() != 'xp' or psutil.__version__ != '3.4.2':
        services_list = psutil.win_service_iter()
        services_running_dict = {}
        for srv in services_list:
            srvname = re.findall("name='(.*)',", str(srv))[0]
            service_temp = psutil.win_service_get(srvname)
            service = service_temp.as_dict()
            # Keep running services
            if service['status'] == 'running':
                services_running_dict[service['name']] = {'Name':service['name'], 'PID':service['pid'],
                                                          'Display_Name':service['display_name'], 'Start_Type':service['start_type'],
                                                          'Username':service['username'], 'Binpath':service['binpath']}
    else:
        import wmi
        wmi_instance = wmi.WMI()
        services_list = wmi_instance.Win32_Service()
        services_running_dict = {}
        for srv in services_list:
            # Keep running services
            if srv.State == 'Running':
                services_running_dict[srv.name] = {'Name':srv.name, 'PID':srv.processid,
                                                   'Display_Name':srv.displayname, 'Start_Type':srv.startmode,
                                                   'Username':srv.startname, 'Binpath':srv.pathname}

    # 3 - Ecriture du fichier CSV
    header = ['Name', 'Display_Name', 'PID', 'Start_Type', 'Username', 'Binpath']
    csv_file = log_file_path + "services.csv"
    writer.write_csv(csv_file, header, services_running_dict)

    # 4 - Transformation du CSV en HTML
    htmltxt = writer.csv2html(csv_file, 'Running services')

    # 5 - Ecriture de la fin du log
    writer.writelog(log_file, str(len(services_running_dict)) + ' running services :<br>\n')
    writer.writelog(log_file, htmltxt)
    writer.writelog(log_file, '\n</div>\n')

    return services_running_dict
Exemplo n.º 25
0
def getService(name):
    service = None
        
    try:
        service = psutil.win_service_get(name)
        service = service.as_dict()
    except Exception as ex:
        textwriter.write('Exception: {}'.format(str(ex)))
        
    return service
Exemplo n.º 26
0
def get_service(name):
    service = None
    try:
        service = psutil.win_service_get(name)
        service = service.as_dict()
    except Exception as ex:
        # raise psutil.NoSuchProcess if no service with such name exists
        print(str(ex))

    return service
Exemplo n.º 27
0
def _is_docker_running():
    return True
    service = None
    try:
        service = psutil.win_service_get('docker')
        service = service.as_dict()
    except Exception:
        pass

    return service is not None
Exemplo n.º 28
0
 def get_service(self):
     """get a service handle"""
     if self.service:
         return
     # pylint: disable=broad-except
     try:
         self.service = psutil.win_service_get("ArangoDB")
     except Exception as exc:
         logging.error("failed to get service! - %s", str(exc))
         return
def stop_update_process():
    # core windows update services are "wuauserv" and "TrustedInstaller"
    # another windows services will released by Microsoft in the future.
    # such as 'WaaSMedicSvc', 'sedsvc'
    windows_update_services_list = ["wuauserv", "TrustedInstaller"]

    for service_name in windows_update_services_list:
        pid = psutil.win_service_get(name=service_name).pid()
        if pid > 0:  # not None
            psutil.Process(pid=pid).terminate()
Exemplo n.º 30
0
def service_status(my_service_name):
    '''
    :return: The current status for the given service
    '''
    try:
        y = psutil.win_service_get(my_service_name)
        r_value = y.status()
    except psutil.NoSuchProcess:
        print("No such service \n")
        r_value = "No such service"

    return r_value
Exemplo n.º 31
0
def checkServiceStatus(server):
    status = None

    service = psutil.win_service_get(server)
    status = service.as_dict()
    print("%s (%s)" % (status['name'], status['display_name']))
    print("status: %s, start: %s, username: %s, pid: %s" %
          (status['status'], status['start_type'], status['username'],
           status['pid']))
    print("binpath: %s" % status['binpath'])

    return status
Exemplo n.º 32
0
    def enum(self):
        """ Enum installed services and return running and stopped
		to arrays """
        for service in psutil.win_service_iter():
            status = psutil.win_service_get(service.name())

            if "running" in status.status():
                self.running_services.append(status.name())
            else:
                self.stopped_services.append(status.name())

        return (self.running_services, self.stopped_services)
Exemplo n.º 33
0
 def test_win_service_iter(self):
     valid_statuses = set([
         "running",
         "paused",
         "start",
         "pause",
         "continue",
         "stop",
         "stopped",
     ])
     valid_start_types = set([
         "automatic",
         "manual",
         "disabled",
     ])
     valid_statuses = set([
         "running",
         "paused",
         "start_pending",
         "pause_pending",
         "continue_pending",
         "stop_pending",
         "stopped"
     ])
     for serv in psutil.win_service_iter():
         data = serv.as_dict()
         self.assertIsInstance(data['name'], basestring)
         self.assertNotEqual(data['name'].strip(), "")
         self.assertIsInstance(data['display_name'], basestring)
         self.assertIsInstance(data['username'], basestring)
         self.assertIn(data['status'], valid_statuses)
         if data['pid'] is not None:
             psutil.Process(data['pid'])
         self.assertIsInstance(data['binpath'], basestring)
         self.assertIsInstance(data['username'], basestring)
         self.assertIsInstance(data['start_type'], basestring)
         self.assertIn(data['start_type'], valid_start_types)
         self.assertIn(data['status'], valid_statuses)
         self.assertIsInstance(data['description'], basestring)
         pid = serv.pid()
         if pid is not None:
             p = psutil.Process(pid)
             self.assertTrue(p.is_running())
         # win_service_get
         s = psutil.win_service_get(serv.name())
         # test __eq__
         self.assertEqual(serv, s)