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))
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!")
def winservices(): """ $ function winservices return string of List all Windows services installed. AeLookupSvc (Application Experience) status: stopped, start: manual, username: localSystem, pid: None binpath: C:\Windows\system32\svchost.exe -k netsvcs ALG (Application Layer Gateway Service) status: stopped, start: manual, username: NT AUTHORITY\LocalService, pid: None binpath: C:\Windows\System32\alg.exe APNMCP (Ask Update Service) status: running, start: automatic, username: LocalSystem, pid: 1108 binpath: "C:\Program Files (x86)\AskPartnerNetwork\Toolbar\apnmcp.exe" AppIDSvc (Application Identity) status: stopped, start: manual, username: NT Authority\LocalService, pid: None binpath: C:\Windows\system32\svchost.exe -k LocalServiceAndNoImpersonation Appinfo (Application Information) status: stopped, start: manual, username: LocalSystem, pid: None binpath: C:\Windows\system32\svchost.exe -k netsvcs """ result = "" if os.name != 'nt': return "platform not supported (Windows only)" for service in psutil.win_service_iter(): info = service.as_dict() result = result + "\n%r (%r)\n" % (info['name'], info['display_name']) result = result + "status: %s, start: %s, username: %s, pid: %s\n" % ( info['status'], info['start_type'], info['username'], info['pid']) result = result + "binpath: %s" % info['binpath'] return result
def get_services(): try: svc = [x.as_dict() for x in psutil.win_service_iter()] except Exception: svc = {"error": "error getting services"} finally: return svc
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))
def main(): for service in psutil.win_service_iter(): info = service.as_dict() print("%r (%r)" % (info['name'], info['display_name'])) print("status: %s, start: %s, username: %s, pid: %s" % ( info['status'], info['start_type'], info['username'], info['pid'])) print("binpath: %s" % info['binpath']) print("")
def getServices(self, file_zip): with TemporaryFile('w+', newline='') as file_temp: csv_temp = csv.writer(file_temp) csv_temp.writerow(('Status', )) for serv in psutil.win_service_iter(): csv_temp.writerow((serv.status(), )) file_temp.seek(0) file_zip.writestr('services.csv', file_temp.file.read())
def main(): for service in psutil.win_service_iter(): info = service.as_dict() print("%s (%s)" % (info['name'], info['display_name'])) print("status: %s, start: %s, username: %s, pid: %s" % ( info['status'], info['start_type'], info['username'], info['pid'])) print("binpath: %s" % info['binpath']) print("")
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
def check_install(): # 检测本机是否已安装AgentService服务 service_list = [] for service in psutil.win_service_iter(): service_list.append(service.name()) if "AgentService" in service_list: return True else: return False
def get_services_via_psutil(self, *args, **kwargs): services = {} for service in psutil.win_service_iter(): name = service.name() if service.status() == 'running': services[name] = 'running' else: services[name] = 'stopped' return services
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
def running_SERVICES(): try: services='' win_services= psutil.win_service_iter() for win_service in win_services: services += colored(win_service, 'cyan')+'\n' TOWER.sendall(str.encode(SUCCESS+'Client running services:\n\n{}'.format(services))) #print (SUCCESS+'Your running services:\n\n{}'.format(services)) except Exception as get_serv_err: TOWER.sendall(str.encode(ERROR+'Unable to retrieve client running services.\nReason: {}'.format(get_serv_err)))
def listservices(namefilter='', status=''): if sys.platform != 'win32': return {} services = {} for i in psutil.win_service_iter(): if namefilter and namefilter.lower() not in i.name().lower( ) or status and i.status() != status: continue services[i.binpath()] = i.as_dict() return services
def get_instances(self): # type: () -> str """Gets all instances""" # TODO: Clarify if this is really the windows pendant out = "" for proc in psutil.win_service_iter(): if "postgres" in proc.name().lower() and proc.status( ) == "running": out += "%s %s\n" % (proc.pid(), proc.binpath()) return out.rstrip()
def list_services(): x = 0 for serv in psutil.win_service_iter(): x += 1 try: servname = serv.name() servdisp = serv.display_name() servstatus = serv.status() except Exception as ex: print("reaised exc", ex) pass
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)
def win_services(log_file): dict = {} date = datetime.datetime.now() log_file.write("{}\n".format(date)) for iter in psutil.win_service_iter(): service_name = iter.name() service_status = iter.status() linew = "{} {}\n".format(service_name, service_status) log_file.write(linew) dict[service_name] = service_status log_file.write("\n") log_file.close() return dict
def popupevent_win_services(self,obj): win_services_information = list(psutil.win_service_iter()) layout = BoxLayout(orientation='vertical') win_services_tomb = '' for i in win_services_information: win_services_tomb += ' '.join(str(i))+'\n\n' szoveg = TextInput(text=win_services_tomb) kilepes = Button(text='Exit') layout.add_widget(szoveg) layout.add_widget(kilepes) popup = Popup(title='Services', content=layout, auto_dismiss=False, size=(400, 400)) kilepes.bind(on_press=popup.dismiss) popup.open()
def ServicesList(self): try: results = [] for service in psutil.win_service_iter(): try: results.append(service.as_dict()) except Exception as e: print(str(e)) result = json.dumps(results) return [True, result] except Exception as e: return [False, "Plugin Services Failed, reason: " + str(e)]
def Windows_WriteFileLog(logServiceFile): listOfFileWindows = {} log_file = open(logServiceFile, "a") dateNow = datetime.now() log_file.write("{}\n".format(dateNow)) for service in psutil.win_service_iter(): serviceName = service.name() serviceStatus = service.status() line_to_write = serviceName + " " + serviceStatus + "\n" log_file.write(line_to_write) listOfFileWindows[serviceName] = serviceStatus log_file.write("\n") log_file.close() return listOfFileWindows
def services(): try: sys.stdout = open('./output/services.txt', 'w') for service in psutil.win_service_iter(): info = service.as_dict() print("%r (%r)" % (info['name'], info['display_name'])) print("status: %s, start: %s, username: %s, pid: %s" % (info['status'], info['start_type'], info['username'], info['pid'])) print("binpath: %s" % info['binpath']) print("") except Exception as e: print(e)
def sampleToServiceListWin(serviceListFile): dictToReturn = {} # class datetime.datetime give a combination of a date and a time. dateWtime = datetime.datetime.now() serviceListFile.write("Sampling date and time: {}\n".format(dateWtime)) for iter in psutil.win_service_iter(): serviceName = iter.name() serviceStatus = iter.status() lineToWrite = "{} {}\n".format(serviceName, serviceStatus) serviceListFile.write(lineToWrite) dictToReturn[serviceName] = serviceStatus serviceListFile.write("\n") serviceListFile.close() return dictToReturn
def _find_agent_service(self): for service in psutil.win_service_iter(): params = service.as_dict() binpath = params.get('binpath', '') if SERVICE_AGENT_EXE not in binpath: continue parameters = get_args_cmdline(binpath) if parameters.port and int(parameters.port) == self.port: self.service = service self.parameters = parameters break
def show_me(): OKS = {} alias = {'automatic': '自动', 'manual': '手动', 'disabled': '禁用'} for i in psutil.win_service_iter(): try: item = i.as_dict() item['start_type'] = alias.get(item['start_type'], item['start_type']) if item['status'] == 'running': OKS[item['name']] = item['start_type'] except (psutil.NoSuchProcess, FileNotFoundError): pass print('OKS = ', OKS) NOT_OKS = {} for i in psutil.win_service_iter(): try: item = i.as_dict() item['start_type'] = alias.get(item['start_type'], item['start_type']) if item['name'] not in OKS: NOT_OKS[item['name']] = item['start_type'] except (psutil.NoSuchProcess, FileNotFoundError): pass print('NOT_OKS = ', NOT_OKS)
def win_service_info(self, name): ''' # s = psutil.win_service_get('alg') # print(s.display_name(),s.username(),s.name(),s.description()) :param name: :return: ''' win_list = list(psutil.win_service_iter()) if name in [i.name() for i in win_list]: s = psutil.win_service_get(name) return s.as_dict() else: print("Name is invalid...Just like this:") print(str([i.name() for i in win_list])) return None
def __get_winservice(self): """Retrieve windows service information""" if Config().PLATFORM != 'win32': raise NotImplementedError( "Cannot get Windows service information on a non-win32 system") data = [] for srv in psutil.win_service_iter(): data.append({ 'name': srv.name(), 'binpath': srv.binpath(), 'username': srv.username(), 'start_type': srv.start_type(), 'status': srv.status(), 'pid': srv.pid() }) return data
def GetService(self): # services = psutil.win_service_iter() # for s in services: # service_name = s.name() service_status = s.status() service_user = s.username() service_type = s.start_type() service_pid = s.pid() # self.service_list.append([ service_name, service_type, service_status, service_user, service_pid ])
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)
def get_sids_from_windows(): """return ORACLE_SID ORACLE_HOME list from windows service defs""" sids = [] for _p in psutil.win_service_iter(): info = _p.as_dict() if 'OracleService' in info['name']: # print(info) # print(info['name']) # print(info['binpath']) oracle_sid = info['name'].strip('OracleService') oracle_home = os.path.dirname( os.path.dirname(info['binpath'])) sids.append([oracle_sid, oracle_home]) return sids
def is_installed_as_win_service(self): """ returns True if mongodb is installed as a windows service :return: """ if platform == 'win32': win_services = list(psutil.win_service_iter()) mongo_service = [] for service in win_services: if 'mongo' in service.display_name().lower(): mongo_service.append(service) is_service = len(mongo_service) > 0 return is_service else: Console.error( f'Windows platform function called instead of {platform}') return False
def start_monitor(current_os, interval): # create new logger objects service_list_logger = pmon_logging.pmon_logger('svclist', 'serviceList.txt') status_logger = pmon_logging.pmon_logger('statlog', 'Status_Log.txt') #pick up where we left off: get last sample and processes from last sample_id sample_id = int(pmon_logging.get_last_sid()) ps_old = pmon_logging.get_processes_by_sid(sample_id) sample_id += 1 try: while True: # list to store our services ps_new = [] if current_os == 'Linux': for process in psutil.process_iter(): # we discern daemons by checking whether they are linked to a terminal if process.terminal() is None: ps_new.append([str(process.pid), process.name()]) else: #must be windows for process in psutil.win_service_iter(): ps_new.append([str(process.pid()), process.name()]) #take difference between old and new lists ps_born = [ i for i in ps_old + ps_new if i in ps_new and i not in ps_old ] ps_died = [ i for i in ps_old + ps_new if i in ps_old and i not in ps_new ] #logging and printing service_list_logger.log_serviceList(ps_new, sample_id) status_logger.log_Status_Log(ps_born, 'created', True) status_logger.log_Status_Log(ps_died, 'terminated', True) #iteration ps_old = ps_new sample_id += 1 time.sleep(interval) except KeyboardInterrupt: print('Program terminated by user.')
print "\n" print "net_if_stats is ",psutil.net_if_stats() print "boot_time is ",psutil.boot_time() print "pids is ",psutil.pids() p=psutil.Process(8924) print p.name() print p.exe() print "cwd is ",p.cwd() print "cmdline is ",p.cmdline() print p.status() print p.username() print p.create_time() print p.memory_full_info() print p.memory_info() print "io_counters is",p.io_counters() print p.open_files() print p.connections() print p.num_ctx_switches() print p.nice() print psutil.test() for p in psutil.process_iter(): print p for i in list(psutil.win_service_iter()): print i
def list_service(): service_dict = OrderedDict() for service in psutil.win_service_iter(): service_dict[service.name()] = service.display_name() return service_dict
def test_win_service_get_description(self): name = next(psutil.win_service_iter()).name() fun = psutil._psplatform.cext.winservice_query_descr self.execute(fun, name)
def test_win_service_get_status(self): name = next(psutil.win_service_iter()).name() fun = psutil._psplatform.cext.winservice_query_status self.execute(fun, name)
def test_win_service_get_description(self): name = next(psutil.win_service_iter()).name() self.execute(cext.winservice_query_descr, name)
def test_win_service_get_status(self): name = next(psutil.win_service_iter()).name() self.execute(cext.winservice_query_status, name)
def test_win_service_get_config(self): name = next(psutil.win_service_iter()).name() self.execute(cext.winservice_query_config, name)