Server IP : 92.204.138.22 / Your IP : 3.145.71.240 Web Server : Apache System : Linux ns1009439.ip-92-204-138.us 4.18.0-553.8.1.el8_10.x86_64 #1 SMP Tue Jul 2 07:26:33 EDT 2024 x86_64 User : internationaljou ( 1019) PHP Version : 7.4.33 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /home/internationaljou/public_html/admin/js/BROKY_ADMIN/alfasymlink/root/lib/panopta-agent/library/ |
Upload File : |
from datetime import datetime import agent_util import platform import os import sys import logging import socket try: # Python 2.x import httplib except: import http.client as httplib try: import psutil except: psutil = None try: import distro except: distro = None try: import json except ImportError: try: import simplejson as json # it's possible that we may not need json for the action that we're taking. # for example, for the rpm post install script, on a python version that # doesn't have json, we'll get this far in the code. but the post # install doesn't use json, so we're fine except ImportError: json = None def mac_address_octets(n): for i in xrange(6): yield n & 0xFF n >>= 8 def int_to_mac_address(n): """ Expresses a decimal integer in standard MAC address format ex: 7267271067680 -> '06:9c:0b:1c:48:20' """ values = ['%02x' % a for a in mac_address_octets(n)] return ':'.join(reversed(values)) class Inspector(object): SOURCE_LIST_PATHS = ['/etc/apt/sources.list', '/etc/yum.repos.d/panopta.repo'] PANOPTA_REPO = 'http://packages.panopta.com/' def __init__(self, agent): self.agent = agent def get_all_facts(self): facts = {} facts.update(self.get_phacter_facts()) facts.update(self.get_agent_facts()) facts.update(self.get_python_facts()) facts.update(self.get_process_facts()) facts.update(self.get_mac_addresses()) facts.update(self.get_hardware_facts()) facts.update(self.get_time_facts()) facts.update(self.get_hostname()) if sys.version_info >= (2, 6, 0): # Cloud detection, but only if we're on a new enough Python to have timeout facts.update(self.get_cloud_facts()) return facts def get_hostname(self): facts = {} facts['hostname'] = socket.getfqdn() return facts def get_time_facts(self): facts = {} try: retcode, output = agent_util.execute_command("ls -l /etc/localtime") timezone = "/".join(output.strip().split("/")[-2:]) facts['timezone'] = timezone except: log = logging.getLogger(self.__class__.__name__) log.exception("Unable to get Time Zone") return facts def get_phacter_facts(self): facts = {} # Phacter requires Python >=2.7 and only works for darwin, linux, and windows if sys.version_info >= (2, 7) and platform.system().lower() in ['darwin', 'linux', 'windows']: try: import phacter except: log = logging.getLogger(self.__class__.__name__) log.info("Unable to import phacter, skipping system fact collection") return {} for fact in phacter.phacts: try: facts[fact] = phacter[fact] except Exception: _, e, _ = sys.exc_info() log = logging.getLogger(self.__class__.__name__) log.warn("Could not collect fact '%s': %s", fact, e) continue return facts def get_hardware_facts(self): """ Gather CPU and memory specs for the machine """ facts = {"hardware": {}} try: retcode, output = agent_util.execute_command("lscpu") for line in output.strip().split("\n"): try: key, value = line.strip().split(":", 1) except: continue key = key.strip().lower().replace("(s)", "").replace(" ", "_") value = value.strip() facts["hardware"][key] = value except: log = logging.getLogger(self.__class__.__name__) log.exception("Unable to get CPU hardware facts") try: retcode, output = agent_util.execute_command("free -m") for line in output.strip().split("\n"): fields = line.strip().split() if fields[0].lower().startswith("mem"): facts["hardware"]["mem_total"] = int(fields[1]) if fields[0].lower().startswith("swap"): facts["hardware"]["swap_total"] = int(fields[1]) except: log = logging.getLogger(self.__class__.__name__) log.exception("Unable to get memory hardware facts") return facts def get_agent_facts(self): facts = {} # This is a little hokey, but the last time this file's metadata changed # *should* be when this file whas created, ie. when the Agent was # installed. I thought this was better than storing the install time in # the local database, since there is a possibility that it could get # corrupted. facts['installed_time'] = os.path.getctime(os.path.abspath(__file__)) facts['used_manifest'] = os.path.exists(self.agent.manifest_file) facts['installed_from_repo'] = False for source_list_path in self.SOURCE_LIST_PATHS: if os.path.exists(source_list_path): try: source_list = open(source_list_path) facts['installed_from_repo'] = self.PANOPTA_REPO in source_list.read() source_list.close() if facts['installed_from_repo']: break except: pass # Set the agent brand, default to Panopta unless we have an FM-Agent config file facts["agent_brand"] = os.path.exists("/etc/fm-agent") and "fortimonitor" or "panopta" return facts def get_python_facts(self): facts = {"python": {}} facts["python"]["platform"] = platform.platform() facts["python"]["processor"] = platform.processor() facts["python"]["version"] = platform.python_version() facts["python"]["uname"] = platform.uname() try: facts["python"]["dist"] = platform.dist() except AttributeError: # Removed in Python 3.8. # https://docs.python.org/2.7/library/platform.html#platform.linux_distribution if distro: facts["python"]["dist"] = ' '.join(distro.linux_distribution()) facts["python"]["sys_platform"] = sys.platform return facts def get_cloud_facts(self): facts = {} # Try Amazon try: h = httplib.HTTPConnection("169.254.169.254", timeout=5) h.request("GET", "/latest/dynamic/instance-identity/document") r = h.getresponse() if r.status == 200: data = json.loads(r.read()) facts["cloud_provider"] = "aws" facts["cloud_instance_id"] = data["instanceId"] facts["cloud_metadata"] = data return facts except: pass # Try Google try: headers = {"Metadata-Flavor": "Google"} h = httplib.HTTPConnection("metadata.google.internal", timeout=5) h.request("GET", "/computeMetadata/v1/instance/?recursive=true", headers=headers) r = h.getresponse() if r.status == 200: data = json.loads(r.read()) facts["cloud_provider"] = "gcp" facts["cloud_instance_id"] = data["id"] # Strip out sensitive keys if "serviceAccounts" in data: del data["serviceAccounts"] for key, value in data.get('attributes', {}).items(): if key in ['/attribute', '/sshkeys', '/vmdnssetting', '/enable-oslogin']: data['attributes'].pop(key) facts["cloud_metadata"] = data try: manifest = self.agent.get_manifest() enabled_gcp_attributes = manifest.get('agent', 'enable_gcp_attributes') == 'true' facts["cloud_metadata"]["enable_gcp_attributes"] = enabled_gcp_attributes except Exception: log = logging.getLogger(self.__class__.__name__) log.exception('Unable to parse manifest file to determine gcp attributes actions.') return facts except: pass # Try Azure try: headers = {"Metadata": "true"} h = httplib.HTTPConnection("169.254.169.254", timeout=5) h.request("GET", "/metadata/instance?api-version=2017-04-02", headers=headers) r = h.getresponse() if r.status == 200: data = json.loads(r.read()) facts["cloud_provider"] = "azure" facts["cloud_instance_id"] = data["compute"]["vmId"] facts["cloud_metadata"] = data return facts except: pass # No cloud detected return {} def get_process_facts(self): facts = {} if psutil is None: return facts processes = set() for proc in psutil.process_iter(): processes.add(proc.name()) facts["processes"] = list(processes) return facts def mac_address_iter(self): import psutil for iface, addrs in psutil.net_if_addrs().iteritems(): for addr in addrs: if addr.family != psutil.AF_LINK: continue if addr.address == '00:00:00:00:00:00': continue yield addr.address def get_mac_addresses(self): facts = {} try: import uuid facts['uuid_getnode'] = int_to_mac_address(uuid.getnode()) except: log = logging.getLogger(self.__class__.__name__) log.info("Unable to import uuid module. Skipping MAC address fact collection.") try: for i, mac_addr in enumerate(self.mac_address_iter()): facts['mac_address_%d' % i] = mac_addr except ImportError: log = logging.getLogger(self.__class__.__name__) log.info("Unable to import psutil, skipping MAC address fact collection") except: log = logging.getLogger(self.__class__.__name__) log.info("Unknown error during MAC address collection") return facts