Exemplo n.º 1
2
def main(vm_name, guest_ip, host_ip, guest_primary_dns, path_logs):
    # Welcome
    print "\n--- AntiVMdetect by Mikael, @nsmfoo (modified by Jose Carlos R.) ---"
    print bcolors.OKGREEN + " [*]" + bcolors.ENDC + " Creating VirtualBox modifications .."

    dmi_info = {}

    for v in dmidecode.bios().values():
        if type(v) == dict and v["dmi_type"] == 0:
            dmi_info["DmiBIOSVendor"] = v["data"]["Vendor"]
            dmi_info["DmiBIOSReleaseDate"] = v["data"]["Relase Date"]
            dmi_info["DmiBIOSVersion"] = v["data"]["Version"]
            biosversion = v["data"]["BIOS Revision"]

    try:
        dmi_info["DmiBIOSReleaseMajor"], dmi_info["DmiBIOSReleaseMinor"] = biosversion.split(".", 1)
    except:
        dmi_info["DmiBIOSReleaseMajor"] = "** No value to retrieve **"
        dmi_info["DmiBIOSReleaseMinor"] = "** No value to retrieve **"

        # python-dmidecode does not currently reveal all values .. this is plan B
    dmi_firmware = commands.getoutput("dmidecode -t0")
    try:
        dmi_info["DmiBIOSFirmwareMajor"], dmi_info["DmiBIOSFirmwareMinor"] = (
            re.search("Firmware Revision: ([0-9A-Za-z. ]*)", dmi_firmware).group(1).split(".", 1)
        )
    except:
        dmi_info["DmiBIOSFirmwareMajor"] = "** No value to retrieve **"
        dmi_info["DmiBIOSFirmwareMinor"] = "** No value to retrieve **"

    for v in dmidecode.baseboard().values():
        if type(v) == dict and v["dmi_type"] == 2:
            serial_number = v["data"]["Serial Number"]
            dmi_info["DmiBoardVersion"] = v["data"]["Version"]
            if isinstance(v["data"]["Product Name"], int):
                dmi_info["DmiBoardProduct"] = str(v["data"]["Product Name"]) + " "
            else:
                dmi_info["DmiBoardProduct"] = v["data"]["Product Name"]
            dmi_info["DmiBoardVendor"] = v["data"]["Manufacturer"]

            # This is hopefully not the best solution ..
    try:
        s_number = []
        if serial_number:
            # Get position
            if "/" in serial_number:
                for slash in re.finditer("/", serial_number):
                    s_number.append(slash.start(0))
                    # Remove / from string
                    new_serial = re.sub("/", "", serial_number)
                    new_serial = serial_randomize(0, len(new_serial))
                    # Add / again
                for char in s_number:
                    new_serial = new_serial[:char] + "/" + new_serial[char:]
            else:
                new_serial = serial_randomize(0, len(serial_number))
        else:
            new_serial = "** No value to retrieve **"
    except:
        new_serial = "** No value to retrieve **"

    dmi_info["DmiBoardSerial"] = "string:" + new_serial

    # python-dmidecode does not reveal all values .. this is plan B
    dmi_board = commands.getoutput("dmidecode -t2")
    try:
        asset_tag = re.search("Asset Tag: ([0-9A-Za-z ]*)", dmi_board).group(1)
    except:
        asset_tag = "** No value to retrieve **"

    dmi_info["DmiBoardAssetTag"] = asset_tag

    try:
        loc_chassis = re.search("Location In Chassis: ([0-9A-Za-z ]*)", dmi_board).group(1)
    except:
        loc_chassis = "** No value to retrieve **"

    dmi_info["DmiBoardLocInChass"] = loc_chassis

    # Based on the list from http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.0.0.pdf
    board_dict = {
        "Unknown": 1,
        "Other": 2,
        "Server Blade": 3,
        "Connectivity Switch": 4,
        "System Management Module": 5,
        "Processor Module": 6,
        "I/O Module": 7,
        "Memory Module": 8,
        "Daughter board": 9,
        "Motherboard": 10,
        "Processor/Memory Module": 11,
        "Processor/IO Module": 12,
        "Interconnect board": 13,
    }
    try:
        board_type = re.search("Type: ([0-9A-Za-z ]+)", dmi_board).group(1)
        board_type = str(board_dict.get(board_type))
    except:
        board_type = "** No value to retrieve **"

    dmi_info["DmiBoardBoardType"] = board_type

    for v in dmidecode.system().values():
        if type(v) == dict and v["dmi_type"] == 1:
            dmi_info["DmiSystemSKU"] = v["data"]["SKU Number"]
            system_family = v["data"]["Family"]
            system_serial = v["data"]["Serial Number"]
            dmi_info["DmiSystemVersion"] = "string:" + v["data"]["Version"]
            dmi_info["DmiSystemProduct"] = v["data"]["Product Name"]
            dmi_info["DmiSystemVendor"] = v["data"]["Manufacturer"]

    if not system_family:
        dmi_info["DmiSystemFamily"] = "Not Specified"
    else:
        dmi_info["DmiSystemFamily"] = system_family

        # Create a new UUID
    newuuid = str(uuid.uuid4())
    dmi_info["DmiSystemUuid"] = newuuid.upper()
    # Create a new system serial number
    dmi_info["DmiSystemSerial"] = "string:" + (serial_randomize(0, len(system_serial)))

    for v in dmidecode.chassis().values():
        dmi_info["DmiChassisVendor"] = v["data"]["Manufacturer"]
        chassi_serial = v["data"]["Serial Number"]
        dmi_info["DmiChassisVersion"] = v["data"]["Version"]
        dmi_info["DmiChassisType"] = v["data"]["Type"]

        # Based on the list from http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.0.0.pdf
    chassi_dict = {
        "Other": 1,
        "Unknown": 2,
        "Desktop": 3,
        "Low Profile Desktop": 4,
        "Pizza Box": 5,
        "Mini Tower": 6,
        "Tower": 7,
        "Portable": 8,
        "Laptop": 9,
        "Notebook": 10,
        "Hand Held": 11,
        "Docking Station": 12,
        "All in One": 13,
        "Sub Notebook": 14,
        "Space-saving": 15,
        "Lunch Box": 16,
        "Main Server Chassis": 17,
        "Expansion Chassis": 18,
        "SubChassis": 19,
        "Bus Expansion Chassis": 20,
        "Peripheral Chassis": 21,
    }
    dmi_info["DmiChassisType"] = str(chassi_dict.get(dmi_info["DmiChassisType"]))
    # python-dmidecode does not reveal all values .. this is plan B
    chassi = commands.getoutput("dmidecode -t3")
    try:
        dmi_info["DmiChassisAssetTag"] = re.search("Asset Tag: ([0-9A-Za-z ]*)", chassi).group(1)
    except:
        dmi_info["DmiChassisAssetTag"] = "** No value to retrieve **"

        # Create a new chassi serial number, added string to make it be taken as a string even if it's a number
    dmi_info["DmiChassisSerial"] = "string:" + str(serial_randomize(0, len(chassi_serial)))

    for v in dmidecode.processor().values():
        dmi_info["DmiProcVersion"] = v["data"]["Version"]
        dmi_info["DmiProcManufacturer"] = v["data"]["Manufacturer"]["Vendor"]
        # OEM strings
    try:
        for v in dmidecode.type(11).values():
            oem_ver = v["data"]["Strings"]["3"]
            oem_rev = v["data"]["Strings"]["2"]
    except:
        pass
    try:
        dmi_info["DmiOEMVBoxVer"] = oem_ver
        dmi_info["DmiOEMVBoxRev"] = oem_rev
    except:
        dmi_info["DmiOEMVBoxVer"] = "** No value to retrieve **"
        dmi_info["DmiOEMVBoxRev"] = "** No value to retrieve **"

        # Write all data collected so far to file
    file_name = "vboxmods-" + vm_name.replace(" ", "_") + ".sh"

    logfile = file(path_logs + "/" + file_name, "w+")
    logfile.write("# Generated on: " + time.strftime("%H:%M:%S") + "\n")

    for k, v in sorted(dmi_info.iteritems()):
        if "** No value to retrieve **" in v:
            logfile.write(
                '# VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/pcbios/0/Config/'
                + k
                + "\t"
                + v
                + "\n"
            )
        else:
            logfile.write(
                'VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/pcbios/0/Config/'
                + k
                + "\t'"
                + v
                + "'\n"
            )
            # Disk information
    disk_dmi = {}
    try:
        if os.path.exists("/dev/sda"):
            # Disk serial
            disk_serial = commands.getoutput(
                "hdparm -i /dev/sda | grep -o 'SerialNo=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'"
            )
            # To avoid exceding 20 bytes serials
            if len(disk_serial) > 20:
                disk_dmi["SerialNumber"] = serial_randomize(0, 20)
            else:
                disk_dmi["SerialNumber"] = serial_randomize(0, len(disk_serial))
                # Check for HP Legacy RAID
        elif os.path.exists("/dev/cciss/c0d0"):
            # Needs smartctl to be able to get the correct information
            if os.path.exists("/usr/sbin/smartctl"):
                hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
                disk_serial = re.search("Serial number:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
                # To avoid exceding 20 bytes serials
                if len(disk_serial) > 20:
                    disk_dmi["SerialNumber"] = serial_randomize(0, 20)
                else:
                    disk_dmi["SerialNumber"] = serial_randomize(0, len(disk_serial))
            else:
                print bcolors.WARNING + "Install smartmontools: apt-get install smartmontools" + bcolors.ENDC
    except OSError:
        print "Haz RAID?"
        print commands.getoutput("lspci | grep -i raid")

        # Disk firmeware rev
    try:
        if os.path.exists("/dev/sda"):
            disk_fwrev = commands.getoutput(
                "hdparm -i /dev/sda | grep -o 'FwRev=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'"
            )
            disk_dmi["FirmwareRevision"] = disk_fwrev
            if len(disk_dmi["FirmwareRevision"]) < 8:
                disk_dmi["FirmwareRevision"] = disk_dmi["FirmwareRevision"][:8]
        elif os.path.exists("/dev/cciss/c0d0"):
            # Needs smartctl to be able to get the correct information
            if os.path.exists("/usr/sbin/smartctl"):
                hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
                disk_dmi["FirmwareRevision"] = (
                    re.search("Revision:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
                )
                if len(disk_dmi["FirmwareRevision"]) < 8:
                    disk_dmi["FirmwareRevision"] = disk_dmi["FirmwareRevision"][:8]
            else:
                print "Install smartmontools: apt-get install smartmontools"
    except OSError:
        print "Haz RAID?"
        print commands.getoutput("lspci | grep -i raid")

        # Disk Model number
    try:
        if os.path.exists("/dev/sda"):
            disk_modelno = commands.getoutput(
                "hdparm -i /dev/sda | grep -o 'Model=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'"
            )
            disk_dmi["ModelNumber"] = disk_modelno
        elif os.path.exists("/dev/cciss/c0d0"):
            # Needs smartctl to be able to get the correct information
            if os.path.exists("/usr/sbin/smartctl"):
                hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
                disk_dmi["ModelNumber"] = re.search("Product:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
            else:
                print "Install smartmontools: apt-get install smartmontools"
    except OSError:
        print "Haz RAID?"
        print commands.getoutput("lspci | grep -i raid")

        # Write more things to file
    for k, v in disk_dmi.iteritems():
        if "** No value to retrieve **" in v:
            logfile.write(
                '# VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/piix3ide/0/Config/PrimaryMaster/'
                + k
                + "\t"
                + v
                + "\n"
            )
        else:
            logfile.write(
                'VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/piix3ide/0/Config/PrimaryMaster/'
                + k
                + "\t'"
                + v
                + "'\n"
            )

            # CD-ROM information
    cdrom_dmi = {}
    if os.path.islink("/dev/cdrom"):
        # CD-ROM serial
        cdrom_serial = commands.getoutput(
            "hdparm -i /dev/cdrom | grep -o 'SerialNo=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'"
        )
        if cdrom_serial:
            cdrom_dmi["ATAPISerialNumber"] = serial_randomize(0, len(cdrom_serial))
        else:
            cdrom_dmi["ATAPISerialNumber"] = "** No value to retrieve **"

            # CD-ROM firmeware rev
        cdrom_fwrev = commands.getoutput("cd-drive | grep Revision | grep  ':' | awk {' print $3 \" \" $4'}")
        cdrom_dmi["ATAPIRevision"] = cdrom_fwrev.replace(" ", "")

        # CD-ROM Model numberA-Za-z0-9_\+\/ .\"-
        cdrom_modelno = commands.getoutput("cd-drive | grep Model | grep  ':' | awk {' print $3 \" \" $4'}")
        cdrom_dmi["ATAPIProductId"] = cdrom_modelno

        # CD-ROM Vendor
        cdrom_vendor = commands.getoutput("cd-drive | grep Vendor | grep  ':' | awk {' print $3 '}")
        cdrom_dmi["ATAPIVendorId"] = cdrom_vendor
    else:
        logfile.write("# No CD-ROM detected: ** No values to retrieve **\n")

        # And some more
    for k, v in cdrom_dmi.iteritems():
        if "** No value to retrieve **" in v:
            logfile.write(
                '# VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/piix3ide/0/Config/SecondaryMaster/'
                + k
                + "\t"
                + v
                + "\n"
            )
        else:
            logfile.write(
                'VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/piix3ide/0/Config/SecondaryMaster/'
                + k
                + "\t'"
                + v
                + "'\n"
            )

            # Get the DSDT image
            # os.system("dd if=/sys/firmware/acpi/tables/DSDT of=DSDT.bin >/dev/null 2>&1")
            # Write to file
            # Da un error de que la tabla ACPI es mayor de 64KB, aunque lo comente, si luego ejecuto el batch dentro del Guest, pasa las pruebas
            # logfile.write('VBoxManage setextradata '+vm_name+' VBoxInternal/Devices/acpi/0/Config/CustomTable\t\'' + os.getcwd() + '/DSDT.bin\'\n')

    acpi_misc = commands.getoutput('acpidump -s | grep DSDT | grep -o "\(([A-Za-z0-9].*)\)" | tr -d "()"')
    acpi_list = acpi_misc.split(" ")
    acpi_list = filter(None, acpi_list)

    logfile.write(
        'VBoxManage setextradata "'
        + vm_name
        + "\" VBoxInternal/Devices/acpi/0/Config/AcpiOemId\t'"
        + acpi_list[1]
        + "'\n"
    )
    logfile.write(
        'VBoxManage setextradata "'
        + vm_name
        + "\" VBoxInternal/Devices/acpi/0/Config/AcpiCreatorId\t'"
        + acpi_list[4]
        + "'\n"
    )
    logfile.write(
        'VBoxManage setextradata "'
        + vm_name
        + "\" VBoxInternal/Devices/acpi/0/Config/AcpiCreatorRev\t'"
        + acpi_list[5]
        + "'\n"
    )

    # Randomize MAC address, based on onboard interface MAC
    mac_seed = ":".join(re.findall("..", "%012x" % uuid.getnode()))[0:9]
    big_mac = mac_seed + "%02x:%02x:%02x" % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    le_big_mac = re.sub(":", "", big_mac)

    # The last thing!
    logfile.write('VBoxManage modifyvm "' + vm_name + '" --macaddress1\t' + le_big_mac + "\n")
    # Done!
    logfile.close()

    print "	Finished: A template shell script has been created named:", file_name
    print bcolors.OKGREEN + "\n [*]" + bcolors.ENDC + " Creating guest based modification file (to be run inside the guest)"

    # Write all data to file
    file_name2 = "vboxmods-" + vm_name.replace(" ", "_") + ".bat"
    logfile = file("/srv/ftp/CopyThisOne!/" + file_name2, "w+")

    manu = acpi_list[1]

    # DSDT
    logfile.write("@reg copy HKLM\HARDWARE\ACPI\DSDT\VBOX__ HKLM\HARDWARE\ACPI\DSDT\\" + manu + " /s /f\n\n")
    logfile.write("@reg delete HKLM\HARDWARE\ACPI\DSDT\VBOX__ /f\n\n")

    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\"
        + manu
        + "\VBOXBIOS HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___"
        + " /s /f\n\n"
    )
    logfile.write("@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\" + manu + "\VBOXBIOS /f\n\n")

    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\00000002 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\"
        + acpi_list[3]
        + " /s /f\n\n"
    )
    logfile.write(
        "@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\" + manu + "\\" + acpi_list[2] + "___\\00000002 /f\n"
    )

    # FADT
    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\"
        + manu
        + "\VBOXFACP HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___  /s /f\n\n"
    )
    logfile.write("@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\" + manu + "\VBOXFACP /f\n")
    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\00000001 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\"
        + acpi_list[3]
        + " /s /f\n\n"
    )
    logfile.write(
        "@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\" + manu + "\\" + acpi_list[2] + "___\\00000001 /f\n\n"
    )

    # RSDT
    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\"
        + manu
        + "\VBOXRSDT HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___  /s /f\r\n"
    )
    logfile.write("@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\" + manu + "\VBOXRSDT /f\r\n")
    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\00000001 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\"
        + acpi_list[3]
        + " /s /f\r\n"
    )
    logfile.write(
        "@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\" + manu + "\\" + acpi_list[2] + "___\\00000001 /f\r\n"
    )

    # SystemBiosVersion - TODO: get real values
    logfile.write(
        '@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v SystemBiosVersion /t REG_MULTI_SZ /d "'
        + acpi_list[1]
        + " - "
        + acpi_list[0]
        + '" /f\n\n'
    )
    # VideoBiosVersion - TODO: get real values
    logfile.write(
        '@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v VideoBiosVersion /t REG_MULTI_SZ /d "'
        + acpi_list[0]
        + '" /f\n'
    )
    # SystemBiosDate
    d_month, d_day, d_year = dmi_info["DmiBIOSReleaseDate"].split("/")

    if len(d_year) > 2:
        d_year = d_year[:2]

    logfile.write(
        '@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v SystemBiosDate /t REG_MULTI_SZ /d "'
        + d_month
        + "/"
        + d_day
        + "/"
        + d_year
        + '" /f\n'
    )

    # Prevent WMI identification
    logfile.write(
        '@reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\PlugPlay /v Start /t REG_MULTI_SZ /d "4" /f\r\n'
    )
    # The system have to be rebooted for this to work, don't know why

    #  Disables FW
    logfile.write("netsh firewall set opmode disable\n")
    # Disables windows updates
    logfile.write(
        '@reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v AUOptions /t REG_DWORD /d 1 /f\n'
    )
    # Change the IP and DNS
    shortScript = (
        """
		@echo off

		set _enabled=Habilitado
		set _dedicated=Dedicado

		for /f "tokens=1,2,3*" %%i in ('netsh int show interface') do (
			if %%i equ %_enabled% (
				if %%j equ %_dedicated% (
					netsh int ip set address "%%k %%l" static """
        + guest_ip
        + """ 255.255.255.0 """
        + host_ip
        + """ 1
					netsh int ip set dns "%%k %%l" static """
        + guest_primary_dns
        + """
				 )
			)
		)
		ipconfig /flushdns

		:EOF"""
    )
    logfile.write(shortScript + "\n")

    logfile.close()
    print "	Finished: A Windows batch file has been created named:", file_name2

    return
Exemplo n.º 2
0
	def __init__(self):
		if '0x0100' in system():
			key='0x0100'
		else:
			key='0x0001'

		self.SKU=system()[key]['data']['SKU Number']
		self.serial=system()[key]['data']['Serial Number']
		self.product_name=system()[key]['data']['Product Name']
		self.vendor=system()[key]['data']['Manufacturer']
		self.database=Database()
Exemplo n.º 3
0
    def __init__(self):
        if "0x0100" in system():
            key = "0x0100"
        else:
            key = "0x0001"

        self.SKU = system()[key]["data"]["SKU Number"]
        self.serial = system()[key]["data"]["Serial Number"]
        self.product_name = system()[key]["data"]["Product Name"]
        self.vendor = system()[key]["data"]["Manufacturer"]
        self.database = Database(dbhost, dbuser, dbpass, dbname)
Exemplo n.º 4
0
    def __init__(self):
        import dmidecode
        
        self.intf = netifaces.ifaddresses('eth0')
        #print ('test intf:', self.intf)
        self.mac = self.intf[netifaces.AF_LINK][0]['addr']
        self.ip = self.intf[netifaces.AF_INET][0]['addr']
        self.uname = platform.uname()
        self.system = platform.system()
        self.node = platform.node()
        self.release = platform.release()
        self.version = platform.version()
        self.machine = platform.machine()
        # self.proc=platform.processor()

        #system info exxtracted from BIOS via dmidecode
        self.system = dmidecode.system()
        for v in self.system.values():
            if type(v) == dict and v['dmi_type'] == 1:
                self.manuf = v['data']['Manufacturer'] 
                self.model = v['data']['Product Name']
                self.serial = v['data']['Serial Number']
                
        self.cpuinf = self.cpuinfo()
        self.proc = self.cpuinf['proc0']['model name']
        try:
            self.dns = socket.gethostbyaddr(self.ip)[0]
        except (socket.herror):
            self.dns = ''
        
        self._devices = []
        self.nbdev = 0
        self._cachepart = ''
        self._disks = {}
        self._diskinfo={} #Dictionary with local disks informations
Exemplo n.º 5
0
 def get_system_serial_number(self):
     """
     Find and return the
     Serial number of the local machine
     @author: dkennel
     @return: string
     """
     systemserial = '0'
     if DMI and self.euid == 0:
         try:
             system = dmidecode.system()
             for key in system:
                 try:
                     systemserial = system[key]['data']['Serial Number']
                 except(IndexError, KeyError):
                     continue
         except(IndexError, KeyError):
             # got unexpected data back from dmidecode
             pass
     elif os.path.exists('/usr/sbin/system_profiler'):
         profilerfetch = '/usr/sbin/system_profiler SPHardwareDataType'
         cmd3 = subprocess.Popen(profilerfetch, shell=True,
                                 stdout=subprocess.PIPE,
                                 close_fds=True)
         cmd3output = cmd3.stdout.readlines()
         for line in cmd3output:
             if re.search('Serial Number (system):', line):
                 line = line.split(':')
                 try:
                     systemserial = line[1]
                 except(IndexError, KeyError):
                     pass
     systemserial = systemserial.strip()
     return systemserial
Exemplo n.º 6
0
    def get_system_details(self):
        try:
            system_values = dmidecode.system().values()
        except Exception as ex:
            system_values = []

        vendor = None
        try:
            for entry in system_values:
                if 'data' in entry:
                    if 'Manufacturer' in entry['data']:
                        vendor = entry['data']['Manufacturer']
                        break
        except Exception as ex:
            pass

        model = None
        try:
            for entry in system_values:
                if 'data' in entry:
                    if 'Product Name' in entry['data']:
                        model = entry['data']['Product Name']
                        break
        except Exception as ex:
            pass

        return {'vendor': vendor, 'model': model}
Exemplo n.º 7
0
 def get_system_serial_number(self):
     """
     Find and return the
     Serial number of the local machine
     @author: dkennel
     @return: string
     """
     systemserial = '0'
     if DMI and self.euid == 0:
         try:
             system = dmidecode.system()
             for key in system:
                 try:
                     systemserial = system[key]['data']['Serial Number']
                 except(IndexError, KeyError):
                     continue
         except(IndexError, KeyError):
             # got unexpected data back from dmidecode
             pass
     elif os.path.exists('/usr/sbin/system_profiler'):
         profilerfetch = '/usr/sbin/system_profiler SPHardwareDataType'
         cmd3 = subprocess.Popen(profilerfetch, shell=True,
                                 stdout=subprocess.PIPE,
                                 close_fds=True)
         cmd3output = cmd3.stdout.readlines()
         for line in cmd3output:
             if re.search('Serial Number (system):', line):
                 line = line.split(':')
                 try:
                     systemserial = line[1]
                 except(IndexError, KeyError):
                     pass
     systemserial = systemserial.strip()
     return systemserial
Exemplo n.º 8
0
def machine_info():
    info = dmidecode.system()
    info_keys = info.keys()
    for i in range(len(info_keys)):
        if info[info_keys[i]]['dmi_type'] == 1:
            Product_name = info[info_keys[i]]['data']['Product Name']
            return Product_name
Exemplo n.º 9
0
	def get_system_details(self):
		try:
			system_values = dmidecode.system().values()
		except Exception as ex:
			system_values = []

		vendor = None
		try:
			for entry in system_values:
				if 'data' in entry:
					if 'Manufacturer' in entry['data']:
						vendor = entry['data']['Manufacturer']
						break
		except Exception as ex:
			pass

		model = None
		try:
			for entry in system_values:
				if 'data' in entry:
					if 'Product Name' in entry['data']:
						model = entry['data']['Product Name']
						break
		except Exception as ex:
			pass

		return {'vendor': vendor, 'model': model}
def get_server_serial_number():
    """
    Get the server serial number using dmidecode.
    """
    key = 'Serial Number'
    for dsv in dmidecode.system().values():
        if key in dsv['data']:
            return dsv['data'][key]
    return None
Exemplo n.º 11
0
def get_system_specs():
    SYSdict = {}
    SYSlist = []
    for item in dmidecode.system().values():
        if item['dmi_type'] == 1:
            SYSdict['Manufacturer'] = str(item['data']['Manufacturer'])
            SYSdict['Family'] = str(item['data']['Family'])
            SYSdict['Serial Number'] = str(item['data']['Serial Number'])
            SYSlist.append(SYSdict)
    return SYSlist
Exemplo n.º 12
0
def get_system_specs():
    SYSdict = {}
    SYSlist = []
    for item in dmidecode.system().values():
        if item['dmi_type'] == 1:
            SYSdict['Manufacturer'] = str(item['data']['Manufacturer'])
            SYSdict['Family'] = str(item['data']['Family'])
            SYSdict['Serial Number'] = str(item['data']['Serial Number'])
            SYSlist.append(SYSdict)
    return SYSlist
Exemplo n.º 13
0
  def getSYSTEM(self):
    SYSTEMdict = {}
    for v in dmidecode.system().values():
      if type(v) == dict and v['dmi_type'] == 1:
        SYSTEMdict["Manufacturer"] = str((v['data']['Manufacturer']))
        SYSTEMdict["Product_Name"] = str((v['data']['Product Name']))
        SYSTEMdict["Serial_Number"] = str((v['data']['Serial Number']))
        SYSTEMdict["UUID"] = str((v['data']['UUID']))

    return SYSTEMdict["Manufacturer"], SYSTEMdict["Product_Name"], SYSTEMdict["Serial_Number"], SYSTEMdict["UUID"]
Exemplo n.º 14
0
def getSystem():
    print_head('System Info')
    for v in dmidecode.system().values():
        if type(v) == dict and v['dmi_type'] == 1:
            Systemdict["Manufacturer"] = str((v['data']['Manufacturer']))
            Systemdict["Product Name"] = str((v['data']['Product Name']))
            Systemdict["Serial Number"] = str((v['data']['Serial Number']))

            print "Server Manufacture: %s" % Systemdict["Manufacturer"] 
            print "Server Product Name: %s" % Systemdict["Product Name"] 
            print "Server Serial Number: %s" % Systemdict["Serial Number"] 
Exemplo n.º 15
0
 def get_sys_uuid(self):
     """
     Find and return a unique identifier for the system. On most systems
     this will be the UUID of the system. On Solaris SPARC this will be
     a number that is _hopefully_ unique as that platform doesn't have
     UUID numbers.
     @author: D. Kennel
     @return: string
     """
     uuid = "0"
     if DMI and self.euid == 0:
         try:
             system = dmidecode.system()
             for key in system:
                 try:
                     uuid = system[key]["data"]["UUID"]
                 except (IndexError, KeyError):
                     continue
         except (IndexError, KeyError):
             # got unexpected data back from dmidecode
             pass
     elif os.path.exists("/usr/sbin/dmidecode") and self.euid == 0:
         uuidfetch = "/usr/sbin/dmidecode -s system-uuid"
         cmd1 = subprocess.Popen(uuidfetch, shell=True, stdout=subprocess.PIPE, close_fds=True)
         uuid = cmd1.stdout.readline()
     elif os.path.exists("/usr/sbin/smbios"):
         smbiosfetch = "/usr/sbin/smbios -t SMB_TYPE_SYSTEM 2>/dev/null"
         cmd2 = subprocess.Popen(smbiosfetch, shell=True, stdout=subprocess.PIPE, close_fds=True)
         cmdoutput = cmd2.stdout.readlines()
         for line in cmdoutput:
             if re.search("UUID:", line):
                 line = line.split()
                 try:
                     uuid = line[1]
                 except (IndexError, KeyError):
                     pass
     elif os.path.exists("/usr/sbin/system_profiler"):
         profilerfetch = "/usr/sbin/system_profiler SPHardwareDataType"
         cmd3 = subprocess.Popen(profilerfetch, shell=True, stdout=subprocess.PIPE, close_fds=True)
         cmd3output = cmd3.stdout.readlines()
         for line in cmd3output:
             if re.search("UUID:", line):
                 line = line.split()
                 try:
                     uuid = line[2]
                 except (IndexError, KeyError):
                     pass
     elif platform.system() == "SunOS":
         fetchhostid = "/usr/bin/hostid"
         cmd1 = subprocess.Popen(fetchhostid, shell=True, stdout=subprocess.PIPE, close_fds=True)
         uuid = cmd1.stdout.readline()
     uuid = uuid.strip()
     return uuid
Exemplo n.º 16
0
 def manu(self):
     info = dmidecode.system()
     if len(info) > 0 :
         for i in info :
             try:
                 if info[i]['dmi_type'] == 1 :
                     Manufacturer = info[i]['data']['Manufacturer']
                     Product_Name = info[i]['data']['Product Name']
             except Exception,e:
                 print "Error: ",Exception,":",e
                 Manufacturer = 'General'
                 Product_Name = 'PC'
Exemplo n.º 17
0
def serialnumber():
    """
    序列号
    """
    sm = dmidecode.system()

    for k, v in sm.iteritems():
        try:
            sn = v['data']['Serial Number']
            if sn != "":
                return sn
        except:
            pass
Exemplo n.º 18
0
 def get_host(self):
     info = dmidecode.system()
     info_keys = info.keys()
     for i in range(len(info_keys)):
         if info[info_keys[i]]['dmi_type'] == 1:
             self.result["host_manufacturer"]["value"] = info[
                 info_keys[i]]['data']['Manufacturer']
             self.result["host_platform"]["value"] = info[
                 info_keys[i]]['data']['Product Name']
             self.result["uuid"]["value"] = info[
                 info_keys[i]]['data']['UUID']
             self.result["sn"]["value"] = info[
                 info_keys[i]]['data']['Serial Number']
Exemplo n.º 19
0
def macineType():
    """
    服务器型号
    """
    sysinfo = dmidecode.system()
    
    for k,v in sysinfo.iteritems():
        try:
            machine_type = v['data']['Product Name']
            if machine_type != "":
                return machine_type
        except:
            pass
Exemplo n.º 20
0
def serialnumber():
    """
    序列号
    """
    sm = dmidecode.system()

    for k,v in sm.iteritems():
        try:
            sn = v['data']['Serial Number']
            if sn != "":
                return sn
        except:
            pass
Exemplo n.º 21
0
def macineType():
    """
    服务器型号
    """
    sysinfo = dmidecode.system()

    for k, v in sysinfo.iteritems():
        try:
            machine_type = v['data']['Product Name']
            if machine_type != "":
                return machine_type
        except:
            pass
Exemplo n.º 22
0
def GetSysinfo():
	SysDict = {}
	DriveDict= {}
	SysDict["MEMSize"] = 0
	for v in dmidecode.system().values():
		if type(v) == dict and v['dmi_type'] == 1:
            		SysDict["Mfg"] = str((v['data']['Manufacturer']))
			SysDict["Model"] = str((v['data']['Product Name']))
			SysDict["Serial"] = str((v['data']['Serial Number']))
	for x in dmidecode.processor().values():
		if type(x) == dict and x['dmi_type'] == 4:
			#SysDict["CPUMfg"] = str((x['data']['Manufacturer']))
			#SysDict["CPUFam"] = str((x['data']['Family']))
			#SysDict["CPUVer"] = str((x['data']['Version']))
			SysDict["CPUFrq"] = str((x['data']['Current Speed']))
	for x in dmidecode.memory().values():
                if type(x) == dict and x['dmi_type'] == 17:
                        #SysDict["MEMSize"] = str((x['data']['Size']))
                        SysDict["MEMType"] = str((x['data']['Type']))
                        #SysDict["MEMDeta"] = str((x['data']['Type Detail']))
                        SysDict["MEMSpeed"] = str((x['data']['Speed']))

	command = "grep \"model name\" /proc/cpuinfo | uniq | awk -F\" \" {' print $4 $5 \" \" $6 \" \" $8 '} | sed 's/(.\{1,2\})/ /g'"
        SysDict["CPUName"] = subprocess.check_output(command, shell=True).strip()
	command = "MSiz=0; for Size in $(dmidecode -t 17 | grep \"Size:\" | awk {' print $2 '}); do MSiz=$(($MSiz+$Size)); done; echo $MSiz"
        SysDict["MEMSize"] = subprocess.check_output(command, shell=True).strip()
	command = "dmidecode -t 17 | grep \"Type:\" | awk {' print $2 '} | uniq"
        SysDict["MEMType"] = subprocess.check_output(command, shell=True).strip()
	command = "lspci | grep VGA | awk -F: {' print $3 '}"
        SysDict["Video"] = subprocess.check_output(command, shell=True).strip()
	command = "lspci | grep Audio | awk -F: {' print $3 '}"
        SysDict["Audio"] = subprocess.check_output(command, shell=True).strip()
	command = "lspci | grep Ethernet | awk -F: {' print $3 '}"
        SysDict["Network"] = subprocess.check_output(command, shell=True).strip()

	### Read drive info from lshw -C disk
	command = "lshw -C disk"
	CMDOutput = subprocess.check_output(command, shell=True).strip()
	for line in CMDOutput:
		if "*-disk" in line:
			DiskMod = CMDOutput.stdout[line+2]
			DiskDev = CMDOutput.stdout[line+5]
			DiskSer = CMDOutput.stdout[line+7]
			DiskCap = CMDOutput.stdout[line+8]
			print(DiskMod+"\n")
			print(DiskDev+"\n")
			print(DiskSer+"\n")
			print(DiskCap+"\n")	

	return SysDict
Exemplo n.º 23
0
 def linux(self):
     hardware_dict = {}
     hostname = socket.gethostname()
     for v in dmidecode.system().values():
         if type(v) == dict and v['dmi_type'] == 1:
             manufacturer = v['data']['Manufacturer']
             model = v['data']['Product Name']
             sn = v['data']['Serial Number']
     return {
         'hostname': hostname,
         'manufactory': manufacturer,
         'model': model,
         'sn': sn
     }
Exemplo n.º 24
0
    def dmi_system(item, data=None):
        if not data:
            data = dmidecode.system()
            dmidecode.clear_warnings()

        item = item.lower()

        for key, value in data.iteritems():
            if item == key.lower():
                return value
            if isinstance(value, dict):
                value = dmi_system(item, value)
                if value:
                    return value

        return None
Exemplo n.º 25
0
    def sys_info(self):
        sys = []

        for v in dmidecode.system().values():
            if v['dmi_type'] == 1: #System
                sys.append("Manufacturer: %s" %(v['data']['Manufacturer']))
                sys.append("Product Name: %s" %(v['data']['Product Name']))
                sys.append("Version: %s" %(v['data']['Version']))
                sys.append("Serial Number: %s" %(v['data']['Serial Number']))
                sys.append("UUID: %s" %(v['data']['UUID']))
                sys.append("Wake-up Type: %s" %(v['data']['Wake-Up Type']))
                sys.append("SKU Number: %s" %(v['data']['SKU Number']))
                sys.append("Family: %s" %(v['data']['Family']))


        return sys
Exemplo n.º 26
0
    def dmi_system(item, data=None):
        if not data:
            data = dmidecode.system() #@UndefinedVariable
            dmidecode.clear_warnings() #@UndefinedVariable

        item = item.lower()

        for key, value in data.items():
            if item == key.lower():
                return value.decode('utf-8')
            if isinstance(value, dict) and value:
                value = dmi_system(item, value)
                if value:
                    return value

        return None
Exemplo n.º 27
0
    def dmi_system(item, data=None):
        if not data:
            data = dmidecode.system()  #@UndefinedVariable
            dmidecode.clear_warnings()  #@UndefinedVariable

        item = item.lower()

        for key, value in data.items():
            if item == key.lower():
                return value.decode('utf-8')
            if isinstance(value, dict) and value:
                value = dmi_system(item, value)
                if value:
                    return value

        return None
Exemplo n.º 28
0
def getmodel():
        out_dict = dict()
	dmisysdata = dmidecode.system()
	if not dmisysdata.keys(): # no keys when not sudo
		return failure_output("Error: cannot get model/brand (not sudo?)")
	for key in dmisysdata.keys():
		try:
			model = dmisysdata[key]['data']['Product Name']
		except:
			continue
		try:
			brand = dmisysdata[key]['data']['Manufacturer']
		except:
			continue
        out_dict['model'] = ' '.join([brand, model])
        return out_dict
Exemplo n.º 29
0
def getmodel():
    out_dict = dict()
    dmisysdata = dmidecode.system()
    if not dmisysdata.keys():  # no keys when not sudo
        return failure_output("Error: cannot get model/brand (not sudo?)")
    for key in dmisysdata.keys():
        try:
            model = dmisysdata[key]['data']['Product Name']
        except:
            continue
        try:
            brand = dmisysdata[key]['data']['Manufacturer']
        except:
            continue
    out_dict['model'] = ' '.join([brand, model])
    return out_dict
Exemplo n.º 30
0
 def read_model_info(self):
     """reads model info from HAL"""
     try:
         info = dmidecode.system()['0x0001']['data']
         """ TODO: hardcode here!!! to remove later """
         self.product_id = info['Manufacturer'] + '_' + info['Product Name']
         self.product_name = info['Manufacturer'] + '_' + info['Version']
         self.product_pretty_vendor = info['Manufacturer']
         self.product_pretty_name = info['Version']
         self.product_pretty_id = info['Product Name']
     except:
         print "Warning: unable to get your system model from DMI."
         self.product_id = None
         self.product_name = None
         self.product_pretty_vendor = None
         self.product_pretty_name = None
         self.product_pretty_id = None   
Exemplo n.º 31
0
 def read_model_info(self):
     """reads model info from HAL"""
     try:
         info = dmidecode.system()['0x0001']['data']
         """ TODO: hardcode here!!! to remove later """
         self.product_id = info['Manufacturer'] + '_' + info['Product Name']
         self.product_name = info['Manufacturer'] + '_' + info['Version']
         self.product_pretty_vendor = info['Manufacturer']
         self.product_pretty_name = info['Version']
         self.product_pretty_id = info['Product Name']
     except:
         print "Warning: unable to get your system model from DMI."
         self.product_id = None
         self.product_name = None
         self.product_pretty_vendor = None
         self.product_pretty_name = None
         self.product_pretty_id = None
Exemplo n.º 32
0
    def _getDmidecodeUuid(self):
        if not os.access("/dev/mem", os.R_OK):
            raise Exception("Must run as root")
        try:
            import dmidecode
        except ImportError:
            logger.warn("Can't import dmidecode, falling back to dmidecode command.")
            return self._getDmidecodeUuidCommand()

        try:
            return dmidecode.system()['0x0001']['data']['UUID']
        except Exception:
            # Depending on the target type, various Exceptions can be raised,
            # so just handle any exception.
            # kvm - AttributeError
            # xen - RuntimeError
            logger.warn("Can't use dmidecode library, falling back to mac address")
            return self._getUuidFromMac()
Exemplo n.º 33
0
    def _getDmidecodeUuid(self):
        if not os.access("/dev/mem", os.R_OK):
            raise Exception("Must run as root")
        try:
            import dmidecode
        except ImportError:
            logger.warn("Can't import dmidecode, falling back to dmidecode command.")
            return self._getDmidecodeUuidCommand()

        try:
            return dmidecode.system()['0x0001']['data']['UUID']
        except Exception:
            # Depending on the target type, various Exceptions can be raised,
            # so just handle any exception.
            # kvm - AttributeError
            # xen - RuntimeError
            logger.warn("Can't use dmidecode library, falling back to mac address")
            return self._getUuidFromMac()
Exemplo n.º 34
0
 def get_system_manufacturer(self):
     """
     Find and return the
     System manufacturer
     @author: D. Kennel
     @return: string
     """
     systemmfr = 'Unk'
     if DMI and self.euid == 0:
         try:
             system = dmidecode.system()
             for key in system:
                 try:
                     systemmfr = system[key]['data']['Manufacturer']
                 except (IndexError, KeyError):
                     continue
             systemfr = systemfr.strip()
         except (IndexError, KeyError):
             # got unexpected data back from dmidecode
             pass
     return systemmfr
Exemplo n.º 35
0
 def get_system_manufacturer(self):
     """
     Find and return the
     System manufacturer
     @author: D. Kennel
     @return: string
     """
     systemmfr = 'Unk'
     if DMI and self.euid == 0:
         try:
             system = dmidecode.system()
             for key in system:
                 try:
                     systemmfr = system[key]['data']['Manufacturer']
                 except(IndexError, KeyError):
                     continue
         except(IndexError, KeyError):
             # got unexpected data back from dmidecode
             pass
     systemmfr = systemmfr.strip()
     return systemmfr
Exemplo n.º 36
0
 def read_model_info(self):
     """reads model info using dmidecode module"""
     try:
         current_system = dmidecode.system()                   
         hw_product = current_system['0x0001']['data']['Product Name']
         hw_vendor = current_system['0x0001']['data']['Manufacturer']
         hw_version = current_system['0x0001']['data']['Version']
         product_id = hw_vendor + "_" + hw_product
         self.product_id = product_id.lower()
         product_name = hw_vendor.lower() + "_" + hw_version.lower()
         self.product_name = product_name.lower().replace('/', '-').replace(' ', '_')
         
         self.product_pretty_vendor = hw_vendor
         self.product_pretty_name = hw_version
         self.product_pretty_id = hw_product
     except:
         print "Warning: unable to get your system model from dmidecode"
         self.product_id = ''
         self.product_name = ''
         self.product_pretty_vendor = ''
         self.product_pretty_name = ''
         self.product_pretty_id = ''   
Exemplo n.º 37
0
    def read_model_info(self):
        """reads model info using dmidecode module"""
        try:
            current_system = dmidecode.system()
            hw_product = current_system['0x0001']['data']['Product Name']
            hw_vendor = current_system['0x0001']['data']['Manufacturer']
            hw_version = current_system['0x0001']['data']['Version']
            product_id = hw_vendor + "_" + hw_product
            self.product_id = product_id.lower()
            product_name = hw_vendor.lower() + "_" + hw_version.lower()
            self.product_name = product_name.lower().replace('/', '-').replace(
                ' ', '_')

            self.product_pretty_vendor = hw_vendor
            self.product_pretty_name = hw_version
            self.product_pretty_id = hw_product
        except:
            print "Warning: unable to get your system model from dmidecode"
            self.product_id = ''
            self.product_name = ''
            self.product_pretty_vendor = ''
            self.product_pretty_name = ''
            self.product_pretty_id = ''
Exemplo n.º 38
0
 def get_sys_uuid(self):
     """
     Find and return a unique identifier for the system. On most systems
     this will be the UUID of the system. On Solaris SPARC this will be
     a number that is _hopefully_ unique as that platform doesn't have
     UUID numbers.
     @author: D. Kennel
     @return: string
     """
     uuid = '0'
     if DMI and self.euid == 0:
         try:
             system = dmidecode.system()
             for key in system:
                 try:
                     uuid = system[key]['data']['UUID']
                 except (IndexError, KeyError):
                     continue
         except (IndexError, KeyError):
             # got unexpected data back from dmidecode
             pass
     elif os.path.exists('/usr/sbin/dmidecode') and self.euid == 0:
         uuidfetch = '/usr/sbin/dmidecode -s system-uuid'
         cmd1 = subprocess.Popen(uuidfetch,
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 close_fds=True,
                                 text=True)
         uuid = cmd1.stdout.readline()
     elif os.path.exists('/usr/sbin/smbios'):
         smbiosfetch = '/usr/sbin/smbios -t SMB_TYPE_SYSTEM 2>/dev/null'
         cmd2 = subprocess.Popen(smbiosfetch,
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 close_fds=True,
                                 text=True)
         cmdoutput = cmd2.stdout.readlines()
         line = line.strip()
         for line in cmdoutput:
             if re.search('UUID:', line):
                 line = line.split()
                 try:
                     uuid = line[1]
                 except (IndexError, KeyError):
                     pass
     elif os.path.exists('/usr/sbin/system_profiler'):
         profilerfetch = '/usr/sbin/system_profiler SPHardwareDataType'
         cmd3 = subprocess.Popen(profilerfetch,
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 close_fds=True,
                                 text=True)
         cmd3output = cmd3.stdout.readlines()
         for line in cmd3output:
             line = line.strip()
             if re.search('UUID:', line):
                 line = line.split()
                 try:
                     uuid = line[2]
                 except (IndexError, KeyError):
                     pass
     elif platform.system() == 'SunOS':
         fetchhostid = '/usr/bin/hostid'
         cmd1 = subprocess.Popen(fetchhostid,
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 close_fds=True,
                                 text=True)
         uuid = cmd1.stdout.readline()
         uuid = uuid.strip()
     return uuid
Exemplo n.º 39
0
    def _getdmi(self):
        from pprint import pprint
        DMI = { }


        # get BIOS Data
        #tmp = dmidecode.bios()
        #pprint(tmp)
        for v  in dmidecode.bios().values():
            if type(v) == dict and v['dmi_type'] == 0:
                DMI['bios',0,'BIOS Revision'] = str((v['data']['BIOS Revision']))
                DMI['bios',0,'ROM Size'] = str((v['data']['ROM Size']))
                try:
                    DMI['bios',0,'Release Date'] = str((v['data']['Relase Date']))
                except (KeyError):
                    DMI['bios',0,'Release Date'] = str((v['data']['Release Date']))

                DMI['bios',0,'Runtime Size'] = str((v['data']['Runtime Size']))
                DMI['bios',0,'Vendor'] = str((v['data']['Vendor']))
                DMI['bios',0,'Version'] = str((v['data']['Version']))

        # get System Data
        #tmp = dmidecode.system()
        #pprint(tmp)
        for v  in dmidecode.system().values():
            if type(v) == dict and v['dmi_type'] == 1:
                DMI['system',0,'Family'] = str((v['data']['Family']))
                DMI['system',0,'Manufacturer'] = str((v['data']['Manufacturer']))
                DMI['system',0,'Product Name'] = str((v['data']['Product Name']))
                DMI['system',0,'SKU Number'] = str((v['data']['SKU Number']))
                DMI['system',0,'Serial Number'] = str((v['data']['Serial Number']))
                DMI['system',0,'UUID'] = str((v['data']['UUID']))
                DMI['system',0,'Version'] = str((v['data']['Version']))
                DMI['system',0,'Wake-Up Type'] = str((v['data']['Wake-Up Type']))

        # get BaseBoard Data
        #tmp = dmidecode.baseboard()
        #pprint(tmp)
        for v  in dmidecode.baseboard().values():
            if type(v) == dict and v['dmi_type'] == 2:
                DMI['baseboard',0,'Manufacturer'] = str((v['data']['Manufacturer']))
                DMI['baseboard',0,'Product Name'] = str((v['data']['Product Name']))
                DMI['baseboard',0,'Serial Number'] = str((v['data']['Serial Number']))
                DMI['baseboard',0,'Version'] = str((v['data']['Version']))


        # get chassis Data
        #tmp = dmidecode.chassis()
        #pprint(tmp)
        for v  in dmidecode.chassis().values():
            if type(v) == dict and v['dmi_type'] == 3:
                DMI['chassis',0,'Asset Tag'] = str((v['data']['Asset Tag']))
                DMI['chassis',0,'Boot-Up State'] = str((v['data']['Boot-Up State']))
                DMI['chassis',0,'Lock'] = str((v['data']['Lock']))
                DMI['chassis',0,'Manufacturer'] = str((v['data']['Manufacturer']))
                DMI['chassis',0,'Power Supply State'] = str((v['data']['Power Supply State']))
                DMI['chassis',0,'Security Status'] = str((v['data']['Security Status']))
                DMI['chassis',0,'Serial Number'] = str((v['data']['Serial Number']))
                DMI['chassis',0,'Thermal State'] = str((v['data']['Thermal State']))
                DMI['chassis',0,'Type'] = str((v['data']['Type']))
                DMI['chassis',0,'Version'] = str((v['data']['Version']))

        # get Processor Data
        #tmp = dmidecode.processor()
        #pprint(tmp)
        i = 0
        for v  in dmidecode.processor().values():
            if type(v) == dict and v['dmi_type'] == 4:
                DMI['processor',i,'Asset Tag'] = str((v['data']['Asset Tag']))
                DMI['processor',i,'Characteristics'] = str((v['data']['Characteristics']))
                DMI['processor',i,'Core Count'] = str((v['data']['Core Count']))
                DMI['processor',i,'Core Enabled'] = str((v['data']['Core Enabled']))
                DMI['processor',i,'Current Speed'] =str((v['data']['Current Speed']))
                DMI['processor',i,'External Clock'] = str((v['data']['External Clock']))
                DMI['processor',i,'Family'] = str((v['data']['Family']))
                DMI['processor',i,'L1 Cache Handle'] = str((v['data']['L1 Cache Handle']))
                DMI['processor',i,'L2 Cache Handle'] = str((v['data']['L2 Cache Handle']))
                DMI['processor',i,'L3 Cache Handle'] = str((v['data']['L3 Cache Handle']))
                DMI['processor',i,'Manufacturer'] = str((v['data']['Manufacturer']['Vendor']))
                DMI['processor',i,'Max Speed'] = str((v['data']['Max Speed']))
                DMI['processor',i,'Part Number'] = str((v['data']['Part Number']))
                DMI['processor',i,'Serial Number'] = str((v['data']['Serial Number']))
                DMI['processor',i,'Socket Designation'] = str((v['data']['Socket Designation']))
                DMI['processor',i,'Status'] = str((v['data']['Status']))
                DMI['processor',i,'Thread Count'] = str((v['data']['Thread Count']))
                DMI['processor',i,'Type'] = str((v['data']['Type']))
                DMI['processor',i,'Upgrade'] = str((v['data']['Upgrade']))
                DMI['processor',i,'Version'] = str((v['data']['Version']))
                DMI['processor',i,'Voltage'] = str((v['data']['Voltage']))
                i += 1


        # get Memory Data
        #tmp = dmidecode.memory()
        #pprint(tmp)
        i = 0
        for v  in dmidecode.memory().values():
            if type(v) == dict and v['dmi_type'] == 17 :
                if str((v['data']['Size'])) != 'None':
                    DMI['memory',i,'Data Width'] = str((v['data']['Data Width']))
                    DMI['memory',i,'Error Information Handle'] = str((v['data']['Error Information Handle']))
                    DMI['memory',i,'Form Factor'] = str((v['data']['Form Factor']))
                    DMI['memory',i,'Bank Locator'] = str((v['data']['Bank Locator']))
                    DMI['memory',i,'Locator'] = str((v['data']['Locator']))
                    DMI['memory',i,'Manufacturer'] = str((v['data']['Manufacturer']))
                    DMI['memory',i,'Part Number'] = str((v['data']['Part Number']))
                    DMI['memory',i,'Serial Number'] = str((v['data']['Serial Number']))
                    DMI['memory',i,'Size'] = str((v['data']['Size']))
                    DMI['memory',i,'Speed'] = str((v['data']['Speed']))
                    DMI['memory',i,'Type'] = str((v['data']['Type']))
                    i += 1

        # get cache Data
        #tmp = dmidecode.cache()
        #pprint(tmp)

        # get connector Data
        #tmp = dmidecode.connector()
        #pprint(tmp)

        # get slot Data
        #tmp = dmidecode.slot()
        #pprint(tmp)

        return DMI
Exemplo n.º 40
0
dmi_info['DmiBoardLocInChass'] = loc_chassis

# Based on the list from http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.0.0.pdf
board_dict = {'Unknown': 1, 'Other': 2, 'Server Blade': 3, 'Connectivity Switch': 4, 'System Management Module': 5,
              'Processor Module': 6, 'I/O Module': 7, 'Memory Module': 8, 'Daughter board': 9, 'Motherboard': 10,
              'Processor/Memory Module': 11, 'Processor/IO Module': 12, 'Interconnect board': 13}
try:
    board_type = re.search("Type: ([0-9A-Za-z ]+)", dmi_board).group(1)
    board_type = str(board_dict.get(board_type))
except:
    board_type = '** No value to retrieve **'

dmi_info['DmiBoardBoardType'] = board_type

for v in dmidecode.system().values():
    if type(v) == dict and v['dmi_type'] == 1:
        dmi_info['DmiSystemSKU'] = v['data']['SKU Number']
        system_family = v['data']['Family']
        system_serial = v['data']['Serial Number']
        dmi_info['DmiSystemVersion'] = "string:" + v['data']['Version']
        dmi_info['DmiSystemProduct'] = v['data']['Product Name']
        dmi_info['DmiSystemVendor'] = v['data']['Manufacturer']

if not system_family:
    dmi_info['DmiSystemFamily'] = "Not Specified"
else:
    dmi_info['DmiSystemFamily'] = system_family

# Create a new UUID
newuuid = str(uuid.uuid4())
Exemplo n.º 41
0
        print("#### If this script is first run as root, it should be possible to run this script")
        print("#### as an unprivileged user afterwards, with less warnings.")
        print("####")
        print()
        print()


#. Test for presence of important functions using /dev/mem...  Using the legacy API
#. This does not print any decoded info.  If the call fails, either a warning will
#. be issued or an exception will be raised.  This test is now only used to check
#. for presence of the legacy API, which "under the hood" uses
#. dmidecode.QuerySection(name), where name can be 'bios', 'system', etc.
if root_user:
        print("*** bios ***\n");      dmidecode.bios()
        print_warnings()
        print("*** system ***\n");    dmidecode.system()
        print_warnings()
        print("*** baseboard ***\n"); dmidecode.baseboard()
        print_warnings()
        print("*** chassis ***\n");   dmidecode.chassis()
        print_warnings()
        print("*** processor ***\n"); dmidecode.processor()
        print_warnings()
        print("*** memory ***\n");    dmidecode.memory()
        print_warnings()
        print("*** cache ***\n");     dmidecode.cache()
        print_warnings()
        print("*** connector ***\n"); dmidecode.connector()
        print_warnings()
        print("*** slot ***\n");      dmidecode.slot()
        print_warnings()
Exemplo n.º 42
0
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
'''
Created on '2017/9/21 18:10'
Email: [email protected]
@author: Redheat
'''
import dmidecode
import netifaces
info = dmidecode.system()  #SN,服务器型号
info_keys = info.keys()
dmidecode.memory()  #内存信息
dmidecode.processor()  #处理器信息

for i in range(len(info_keys)):
    if info[info_keys[i]]['dmi_type'] == 1:
        print info[info_keys[i]]['data']['Manufacturer']
        print info[info_keys[i]]['data']['Product Name']

netifaces.interfaces()
netifaces.ifaddresses('eno1')  #IP信息
Exemplo n.º 43
0
    def _getdmi(self):
        from pprint import pprint
        DMI = {}

        # get BIOS Data
        #tmp = dmidecode.bios()
        #pprint(tmp)
        for v in dmidecode.bios().values():
            if type(v) == dict and v['dmi_type'] == 0:
                DMI['bios', 0, 'BIOS Revision'] = str(
                    (v['data']['BIOS Revision']))
                DMI['bios', 0, 'ROM Size'] = str((v['data']['ROM Size']))
                try:
                    DMI['bios', 0, 'Release Date'] = str(
                        (v['data']['Relase Date']))
                except (KeyError):
                    DMI['bios', 0, 'Release Date'] = str(
                        (v['data']['Release Date']))

                DMI['bios', 0, 'Runtime Size'] = str(
                    (v['data']['Runtime Size']))
                DMI['bios', 0, 'Vendor'] = str((v['data']['Vendor']))
                DMI['bios', 0, 'Version'] = str((v['data']['Version']))

        # get System Data
        #tmp = dmidecode.system()
        #pprint(tmp)
        for v in dmidecode.system().values():
            if type(v) == dict and v['dmi_type'] == 1:
                DMI['system', 0, 'Family'] = str((v['data']['Family']))
                DMI['system', 0, 'Manufacturer'] = str(
                    (v['data']['Manufacturer']))
                DMI['system', 0, 'Product Name'] = str(
                    (v['data']['Product Name']))
                DMI['system', 0, 'SKU Number'] = str((v['data']['SKU Number']))
                DMI['system', 0, 'Serial Number'] = str(
                    (v['data']['Serial Number']))
                DMI['system', 0, 'UUID'] = str((v['data']['UUID']))
                DMI['system', 0, 'Version'] = str((v['data']['Version']))
                DMI['system', 0, 'Wake-Up Type'] = str(
                    (v['data']['Wake-Up Type']))

        # get BaseBoard Data
        #tmp = dmidecode.baseboard()
        #pprint(tmp)
        for v in dmidecode.baseboard().values():
            if type(v) == dict and v['dmi_type'] == 2:
                DMI['baseboard', 0, 'Manufacturer'] = str(
                    (v['data']['Manufacturer']))
                DMI['baseboard', 0, 'Product Name'] = str(
                    (v['data']['Product Name']))
                DMI['baseboard', 0, 'Serial Number'] = str(
                    (v['data']['Serial Number']))
                DMI['baseboard', 0, 'Version'] = str((v['data']['Version']))

        # get chassis Data
        #tmp = dmidecode.chassis()
        #pprint(tmp)
        for v in dmidecode.chassis().values():
            if type(v) == dict and v['dmi_type'] == 3:
                DMI['chassis', 0, 'Asset Tag'] = str((v['data']['Asset Tag']))
                DMI['chassis', 0, 'Boot-Up State'] = str(
                    (v['data']['Boot-Up State']))
                DMI['chassis', 0, 'Lock'] = str((v['data']['Lock']))
                DMI['chassis', 0, 'Manufacturer'] = str(
                    (v['data']['Manufacturer']))
                DMI['chassis', 0, 'Power Supply State'] = str(
                    (v['data']['Power Supply State']))
                DMI['chassis', 0, 'Security Status'] = str(
                    (v['data']['Security Status']))
                DMI['chassis', 0, 'Serial Number'] = str(
                    (v['data']['Serial Number']))
                DMI['chassis', 0, 'Thermal State'] = str(
                    (v['data']['Thermal State']))
                DMI['chassis', 0, 'Type'] = str((v['data']['Type']))
                DMI['chassis', 0, 'Version'] = str((v['data']['Version']))

        # get Processor Data
        #tmp = dmidecode.processor()
        #pprint(tmp)
        i = 0
        for v in dmidecode.processor().values():
            if type(v) == dict and v['dmi_type'] == 4:
                DMI['processor', i, 'Asset Tag'] = str(
                    (v['data']['Asset Tag']))
                DMI['processor', i, 'Characteristics'] = str(
                    (v['data']['Characteristics']))
                DMI['processor', i, 'Core Count'] = str(
                    (v['data']['Core Count']))
                DMI['processor', i, 'Core Enabled'] = str(
                    (v['data']['Core Enabled']))
                DMI['processor', i, 'Current Speed'] = str(
                    (v['data']['Current Speed']))
                DMI['processor', i, 'External Clock'] = str(
                    (v['data']['External Clock']))
                DMI['processor', i, 'Family'] = str((v['data']['Family']))
                DMI['processor', i, 'L1 Cache Handle'] = str(
                    (v['data']['L1 Cache Handle']))
                DMI['processor', i, 'L2 Cache Handle'] = str(
                    (v['data']['L2 Cache Handle']))
                DMI['processor', i, 'L3 Cache Handle'] = str(
                    (v['data']['L3 Cache Handle']))
                DMI['processor', i, 'Manufacturer'] = str(
                    (v['data']['Manufacturer']['Vendor']))
                DMI['processor', i, 'Max Speed'] = str(
                    (v['data']['Max Speed']))
                DMI['processor', i, 'Part Number'] = str(
                    (v['data']['Part Number']))
                DMI['processor', i, 'Serial Number'] = str(
                    (v['data']['Serial Number']))
                DMI['processor', i, 'Socket Designation'] = str(
                    (v['data']['Socket Designation']))
                DMI['processor', i, 'Status'] = str((v['data']['Status']))
                DMI['processor', i, 'Thread Count'] = str(
                    (v['data']['Thread Count']))
                DMI['processor', i, 'Type'] = str((v['data']['Type']))
                DMI['processor', i, 'Upgrade'] = str((v['data']['Upgrade']))
                DMI['processor', i, 'Version'] = str((v['data']['Version']))
                DMI['processor', i, 'Voltage'] = str((v['data']['Voltage']))
                i += 1

        # get Memory Data
        #tmp = dmidecode.memory()
        #pprint(tmp)
        i = 0
        for v in dmidecode.memory().values():
            if type(v) == dict and v['dmi_type'] == 17:
                if str((v['data']['Size'])) != 'None':
                    DMI['memory', i, 'Data Width'] = str(
                        (v['data']['Data Width']))
                    DMI['memory', i, 'Error Information Handle'] = str(
                        (v['data']['Error Information Handle']))
                    DMI['memory', i, 'Form Factor'] = str(
                        (v['data']['Form Factor']))
                    DMI['memory', i, 'Bank Locator'] = str(
                        (v['data']['Bank Locator']))
                    DMI['memory', i, 'Locator'] = str((v['data']['Locator']))
                    DMI['memory', i, 'Manufacturer'] = str(
                        (v['data']['Manufacturer']))
                    DMI['memory', i, 'Part Number'] = str(
                        (v['data']['Part Number']))
                    DMI['memory', i, 'Serial Number'] = str(
                        (v['data']['Serial Number']))
                    DMI['memory', i, 'Size'] = str((v['data']['Size']))
                    DMI['memory', i, 'Speed'] = str((v['data']['Speed']))
                    DMI['memory', i, 'Type'] = str((v['data']['Type']))
                    i += 1

        # get cache Data
        #tmp = dmidecode.cache()
        #pprint(tmp)

        # get connector Data
        #tmp = dmidecode.connector()
        #pprint(tmp)

        # get slot Data
        #tmp = dmidecode.slot()
        #pprint(tmp)

        return DMI
Exemplo n.º 44
0
    def getData(self, options):
        """
        Method getData

        Gets all information for system asset type

        @type options: dict
        @param options: passed options
        @rtype: void
        """
        # getting data from dmidecode and parsing (chassis, system)
        for hwinfo in dmidecode.system().iteritems():
            if hwinfo[1]['dmi_type'] == 1 and type(hwinfo[1]['data']) == dict:
                for iteminfo in hwinfo[1]['data'].iteritems():
                    tmpinfo = {}
                    p = re.compile('\s+')
                    key = p.sub('', iteminfo[0])
                    self.asset_info[0]['System' + key] = str(iteminfo[1])

        for hwinfo in dmidecode.chassis().iteritems():
            if hwinfo[1]['dmi_type'] == 3 and type(hwinfo[1]['data']) == dict:
                for iteminfo in hwinfo[1]['data'].iteritems():
                    tmpinfo = {}
                    p = re.compile('\s+')
                    key = p.sub('', iteminfo[0])
                    self.asset_info[0]['Chassis' + key] = str(iteminfo[1])

        core_count = 0
        core_enabled_count = 0
        thread_count = 0
        phys_cpu_count = 0

        # counting totals for cpus, cores
        for hwinfo in dmidecode.processor().iteritems():
            if hwinfo[1]['dmi_type'] == 4 and type(hwinfo[1]['data']) == dict:
                phys_cpu_count += 1
                for iteminfo in hwinfo[1]['data'].iteritems():
                    if iteminfo[1] is not None and iteminfo[1] != '':
                        p = re.compile('\s+')
                        key = p.sub('', iteminfo[0])
                        if key == 'CoreCount':
                            core_count += iteminfo[1]
                        elif key == 'CoreEnabled':
                            core_enabled_count += iteminfo[1]
                        elif key == 'ThreadCount':
                            thread_count += iteminfo[1]

        # we need this part in case dmidecode doesn't provide information
        # for cores and threads
        if thread_count == 0 or core_count == 0:
            cpuObj = systeminfo.proc.cpu.Cpu(self.confDir, self.cacheDir, self.viewDir)
            cpuObj.getData({})
            logic_count = len(cpuObj.asset_info)
            phys_to_cores = {}

            for logic_cpu in cpuObj.asset_info:
                if logic_cpu.get('physicalid'):
                    phys_cpu = logic_cpu.get('physicalid')
                    cores = int(logic_cpu.get('cpucores'), 0)

                    if not phys_to_cores.get('physcpu' + phys_cpu):
                        phys_to_cores['physcpu' + phys_cpu] = cores
                        core_count += cores

            if logic_count > core_count and phys_cpu_count != 0:
                thread_count = logic_count

        # getting memory info
        self.getMemInfo()

        self.asset_info[0]['OSCoreCount']  = str(core_count)
        self.asset_info[0]['OSCoreEnabled']  = str(core_enabled_count)
        self.asset_info[0]['OSThreadCount']  = str(thread_count)
        self.asset_info[0]['OSPhyscpuCount']  = str(phys_cpu_count)
        load = os.getloadavg()
        self.asset_info[0]['load']  = str(load[0]) + ' ' + str(load[1]) + ' ' + str(load[2])
        self.asset_info[0]['machinetype']  = platform.machine()
        self.asset_info[0]['nodename']  = platform.node()
        self.asset_info[0]['osrelease']  = platform.release()
        self.asset_info[0]['osname']  = platform.system()
        self.asset_info[0]['osversion']  = platform.version()

        # getting info about distribution, first one is deprecated in newer versions of python
        try:
            distinfo = platform.dist()
        except AttributeError:
            distinfo = platform.linux_distribution()

        self.asset_info[0]['distname']  = distinfo[0]
        self.asset_info[0]['distver']  = distinfo[1]
        self.asset_info[0]['distid']  = distinfo[2]
        self.asset_info[0]['toolindex'] = self.asset_info[0]['SystemSerialNumber']
Exemplo n.º 45
0
	def __init__(self):
		#Get all required system info
		for v in dmidecode.system().values():
                	if type(v) == dict and v['dmi_type'] == 1:
                        	self.Mfg = str((v['data']['Manufacturer']))
                        	self.Model = str((v['data']['Product Name']))
                        	self.Serial = str((v['data']['Serial Number']))
		for x in dmidecode.chassis().values():
                        if type(x) == dict and x['dmi_type'] == 3:
				self.FFactor = str((x['data']['Type']))
        	for x in dmidecode.processor().values():
                	if type(x) == dict and x['dmi_type'] == 4:
                        	self.CPUMfg = str((x['data']['Manufacturer']))
                        	self.CPUFam = str((x['data']['Family']))
                        	self.CPUVer = str((x['data']['Version']))
                        	self.CPUFrq = str((x['data']['Current Speed']))
        	for x in dmidecode.memory().values():
                	if type(x) == dict and x['dmi_type'] == 17:
                        	self.MEMSize = str((x['data']['Size']))
                        	self.MEMType = str((x['data']['Type']))
                        	self.MEMDeta = str((x['data']['Type Detail']))
                        	self.MEMSpeed = str((x['data']['Speed']))
		for x in dmidecode.baseboard().values():
                        if type(x) == dict and x['dmi_type'] == 10:
				if str((x['data']['dmi_on_board_devices'][0]['Type'])) == "Video":
					self.Video = str((x['data']['dmi_on_board_devices'][0]['Description']))
				if str((x['data']['dmi_on_board_devices'][0]['Type'])) == "Sound":
                                        self.Audio = str((x['data']['dmi_on_board_devices'][0]['Description']))
				if str((x['data']['dmi_on_board_devices'][0]['Type'])) == "Ethernet":
                                        self.Network = str((x['data']['dmi_on_board_devices'][0]['Description'])) 
		### Workarounds for things python-dmidecode doesn't do
        	command = "grep \"model name\" /proc/cpuinfo | uniq | awk -F\" \" {' print $4 $5 \" \" $6 \" \" $8 '} | sed 's/(.\{1,2\})/ /g'"
	        self.CPUName = subprocess.check_output(command, shell=True).strip()
	        command = "MSiz=0; for Size in $(dmidecode -t 17 | grep \"Size:\" | awk {' print $2 '}); do MSiz=$(($MSiz+$Size)); done; echo $MSiz"
	        self.MEMSize = subprocess.check_output(command, shell=True).strip()
	        command = "dmidecode -t 17 | grep \"Type:\" | awk {' print $2 '} | uniq"
	        self.MEMType = subprocess.check_output(command, shell=True).strip()
		if self.Video is None:
	        	command = "lspci | grep VGA | awk -F: {' print $3 '}"
	        	self.Video = subprocess.check_output(command, shell=True).strip()
		if self.Audio is None:
	        	command = "lspci | grep Audio | awk -F: {' print $3 '}"
	        	self.Audio = subprocess.check_output(command, shell=True).strip()
		if self.Network is None:
	        	command = "lspci | grep Ethernet | awk -F: {' print $3 '}"
	        	self.Network = subprocess.check_output(command, shell=True).strip()
		command = "lspci | grep 802.11 | awk -F: {' print $3 '}"
                self.WiFi = subprocess.check_output(command, shell=True).strip()
		command = "echo \"Not Yet Implemented\""
                self.Battery = subprocess.check_output(command, shell=True).strip()
		### Get hard drive info
		self.Drive = []
		command = "lshw -C disk"
		CMDOutput = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
		Type = None
		Model = None
		Vendor = None
		Device = None
		Serial = None
		Size = 0
		SectSize = 0
		for line in CMDOutput.stdout:
			if "*-" in line:
				#print("Found: "+line)
				Line = line.split('-', 1)
				Type = Line[1].strip()
			if "product:" in line:
				#print("Found: "+line)
				Line = line.split(':', 1)
				Model = Line[1].strip()
			if "vendor:" in line:
				#print("Found: "+line)
				Line = line.split(':', 1)
				Vendor = Line[1].strip()
			if "logical name:" in line:
				#print("Found: "+line)
				Line = line.split(':', 1)
				Device = Line[1].strip()
			if "serial:" in line:
				#print("Found: "+line)
				Line = line.split(':', 1)
				Serial = Line[1].strip()
			if "size:" in line:
				command = "fdisk -l /dev/sda | grep \""+Device+":\" | awk {' print $5 '}"
				Size = subprocess.check_output(command, shell=True).strip()
				#print("Size: "+Size)
				command = "fdisk -l /dev/sda | grep \"Sector\" | awk {' print $4 '}"
				SectSize = subprocess.check_output(command, shell=True).strip()
				#print("SectSize: "+SectSize)
			if "configuration:" in line:
				Dev = Device.split('/', 2)
				if (Type == "cdrom"):
					self.Optical = Vendor+" "+Model
				else:
					if Vendor is None:
						Line = Model.split(' ', 1)
						Vendor = Line[0].strip()
						Model = Line[1].strip()
					self.Drive.append(self.Disk(Type, Model, Vendor, Device, Serial, Size, SectSize))
				Type = None
				Model = None
				Vendor = None
				Device = None
				Serial = None
				Size = 0
				SectSize = 0
Exemplo n.º 46
0
def getSystemInfo():
    # pylint: disable=no-member
    import dmidecode

    return __leafDict(dmidecode.system())
Exemplo n.º 47
0
    'Memory Module': 8,
    'Daughter board': 9,
    'Motherboard': 10,
    'Processor/Memory Module': 11,
    'Processor/IO Module': 12,
    'Interconnect board': 13
}
try:
    board_type = re.search("Type: ([0-9A-Za-z ]+)", dmi_board).group(1)
    board_type = str(board_dict.get(board_type))
except:
    board_type = '** No value to retrieve **'

dmi_info['DmiBoardBoardType'] = board_type

for v in dmidecode.system().values():
    if type(v) == dict and v['dmi_type'] == 1:
        dmi_info['DmiSystemSKU'] = v['data']['SKU Number']
        system_family = v['data']['Family']
        system_serial = v['data']['Serial Number']
        dmi_info['DmiSystemVersion'] = "string:" + v['data']['Version']
        dmi_info['DmiSystemProduct'] = v['data']['Product Name']
        dmi_info['DmiSystemVendor'] = v['data']['Manufacturer']

if not system_family:
    dmi_info['DmiSystemFamily'] = "Not Specified"
else:
    dmi_info['DmiSystemFamily'] = system_family

# Create a new UUID
newuuid = str(uuid.uuid4())
Exemplo n.º 48
0
    def getData(self, options):
        """
        Method getData

        Gets all information for system asset type

        @type options: dict
        @param options: passed options
        @rtype: void
        """
        # getting data from dmidecode and parsing (chassis, system)
        for hwinfo in dmidecode.system().iteritems():
            if hwinfo[1]['dmi_type'] == 1 and type(hwinfo[1]['data']) == dict:
                for iteminfo in hwinfo[1]['data'].iteritems():
                    tmpinfo = {}
                    p = re.compile('\s+')
                    key = p.sub('', iteminfo[0])
                    self.asset_info[0]['System' + key] = str(iteminfo[1])

        for hwinfo in dmidecode.chassis().iteritems():
            if hwinfo[1]['dmi_type'] == 3 and type(hwinfo[1]['data']) == dict:
                for iteminfo in hwinfo[1]['data'].iteritems():
                    tmpinfo = {}
                    p = re.compile('\s+')
                    key = p.sub('', iteminfo[0])
                    self.asset_info[0]['Chassis' + key] = str(iteminfo[1])

        core_count = 0
        core_enabled_count = 0
        thread_count = 0
        phys_cpu_count = 0

        # counting totals for cpus, cores
        for hwinfo in dmidecode.processor().iteritems():
            if hwinfo[1]['dmi_type'] == 4 and type(hwinfo[1]['data']) == dict:
                phys_cpu_count += 1
                for iteminfo in hwinfo[1]['data'].iteritems():
                    if iteminfo[1] is not None and iteminfo[1] != '':
                        p = re.compile('\s+')
                        key = p.sub('', iteminfo[0])
                        if key == 'CoreCount':
                            core_count += iteminfo[1]
                        elif key == 'CoreEnabled':
                            core_enabled_count += iteminfo[1]
                        elif key == 'ThreadCount':
                            thread_count += iteminfo[1]

        # we need this part in case dmidecode doesn't provide information
        # for cores and threads
        if thread_count == 0 or core_count == 0:
            cpuObj = systeminfo.proc.cpu.Cpu(self.confDir, self.cacheDir,
                                             self.viewDir)
            cpuObj.getData({})
            logic_count = len(cpuObj.asset_info)
            phys_to_cores = {}

            for logic_cpu in cpuObj.asset_info:
                if logic_cpu.get('physicalid'):
                    phys_cpu = logic_cpu.get('physicalid')
                    cores = int(logic_cpu.get('cpucores'), 0)

                    if not phys_to_cores.get('physcpu' + phys_cpu):
                        phys_to_cores['physcpu' + phys_cpu] = cores
                        core_count += cores

            if logic_count > core_count and phys_cpu_count != 0:
                thread_count = logic_count

        # getting memory info
        self.getMemInfo()

        self.asset_info[0]['OSCoreCount'] = str(core_count)
        self.asset_info[0]['OSCoreEnabled'] = str(core_enabled_count)
        self.asset_info[0]['OSThreadCount'] = str(thread_count)
        self.asset_info[0]['OSPhyscpuCount'] = str(phys_cpu_count)
        load = os.getloadavg()
        self.asset_info[0]['load'] = str(load[0]) + ' ' + str(
            load[1]) + ' ' + str(load[2])
        self.asset_info[0]['machinetype'] = platform.machine()
        self.asset_info[0]['nodename'] = platform.node()
        self.asset_info[0]['osrelease'] = platform.release()
        self.asset_info[0]['osname'] = platform.system()
        self.asset_info[0]['osversion'] = platform.version()

        # getting info about distribution, first one is deprecated in newer versions of python
        try:
            distinfo = platform.dist()
        except AttributeError:
            distinfo = platform.linux_distribution()

        self.asset_info[0]['distname'] = distinfo[0]
        self.asset_info[0]['distver'] = distinfo[1]
        self.asset_info[0]['distid'] = distinfo[2]
        self.asset_info[0]['toolindex'] = self.asset_info[0][
            'SystemSerialNumber']
Exemplo n.º 49
0
def main(vm_name, guest_ip, host_ip, guest_primary_dns, path_logs):
	# Welcome
	print '\n--- AntiVMdetect by Mikael, @nsmfoo (modified by Jose Carlos R.) ---'
	print bcolors.OKGREEN+' [*]'+bcolors.ENDC+' Creating VirtualBox modifications ..'

	dmi_info = {}

	for v in dmidecode.bios().values():
		if type(v) == dict and v['dmi_type'] == 0:
			dmi_info['DmiBIOSVendor'] = v['data']['Vendor']
			dmi_info['DmiBIOSReleaseDate'] = v['data']['Relase Date']
			dmi_info['DmiBIOSVersion'] = v['data']['Version']
			biosversion = v['data']['BIOS Revision']

	try:
		dmi_info['DmiBIOSReleaseMajor'], dmi_info['DmiBIOSReleaseMinor'] = biosversion.split('.', 1)
	except:
		dmi_info['DmiBIOSReleaseMajor'] = '** No value to retrieve **'
		dmi_info['DmiBIOSReleaseMinor'] = '** No value to retrieve **'

	# python-dmidecode does not currently reveal all values .. this is plan B
	dmi_firmware = commands.getoutput("dmidecode -t0")
	try:
		dmi_info['DmiBIOSFirmwareMajor'], dmi_info['DmiBIOSFirmwareMinor'] = re.search(
			"Firmware Revision: ([0-9A-Za-z. ]*)", dmi_firmware).group(1).split('.', 1)
	except:
		dmi_info['DmiBIOSFirmwareMajor'] = '** No value to retrieve **'
		dmi_info['DmiBIOSFirmwareMinor'] = '** No value to retrieve **'

	for v in dmidecode.baseboard().values():
		if type(v) == dict and v['dmi_type'] == 2:
			serial_number = v['data']['Serial Number']
			dmi_info['DmiBoardVersion'] = v['data']['Version']
			if isinstance(v['data']['Product Name'], int ):
				dmi_info['DmiBoardProduct'] = str(v['data']['Product Name'])+ ' '
			else:
				dmi_info['DmiBoardProduct'] = v['data']['Product Name']
			dmi_info['DmiBoardVendor'] = v['data']['Manufacturer']

	# This is hopefully not the best solution ..
	try:
		s_number = []
		if serial_number:
			# Get position
			if '/' in serial_number:
				for slash in re.finditer('/', serial_number):
					s_number.append(slash.start(0))
					# Remove / from string
					new_serial = re.sub('/', '', serial_number)
					new_serial = serial_randomize(0, len(new_serial))
				# Add / again
				for char in s_number:
					new_serial = new_serial[:char] + '/' + new_serial[char:]
			else:
				new_serial = serial_randomize(0, len(serial_number))
		else:
			new_serial = "** No value to retrieve **"
	except:
		new_serial = "** No value to retrieve **"

	dmi_info['DmiBoardSerial'] = "string:"+new_serial

	# python-dmidecode does not reveal all values .. this is plan B
	dmi_board = commands.getoutput("dmidecode -t2")
	try:
		asset_tag = re.search("Asset Tag: ([0-9A-Za-z ]*)", dmi_board).group(1)
	except:
		asset_tag = '** No value to retrieve **'

	dmi_info['DmiBoardAssetTag'] = asset_tag

	try:
		loc_chassis = re.search("Location In Chassis: ([0-9A-Za-z ]*)", dmi_board).group(1)
	except:
		loc_chassis = '** No value to retrieve **'

	dmi_info['DmiBoardLocInChass'] = loc_chassis

	# Based on the list from http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.0.0.pdf
	board_dict = {'Unknown': 1, 'Other': 2, 'Server Blade': 3, 'Connectivity Switch': 4, 'System Management Module': 5,
				  'Processor Module': 6, 'I/O Module': 7, 'Memory Module': 8, 'Daughter board': 9, 'Motherboard': 10,
				  'Processor/Memory Module': 11, 'Processor/IO Module': 12, 'Interconnect board': 13}
	try:
		board_type = re.search("Type: ([0-9A-Za-z ]+)", dmi_board).group(1)
		board_type = str(board_dict.get(board_type))
	except:
		board_type = '** No value to retrieve **'

	dmi_info['DmiBoardBoardType'] = board_type

	for v in dmidecode.system().values():
		if type(v) == dict and v['dmi_type'] == 1:
			dmi_info['DmiSystemSKU'] = v['data']['SKU Number']
			system_family = v['data']['Family']
			system_serial = v['data']['Serial Number']
			dmi_info['DmiSystemVersion'] = "string:" + v['data']['Version']
			dmi_info['DmiSystemProduct'] = v['data']['Product Name']
			dmi_info['DmiSystemVendor'] = v['data']['Manufacturer']

	if not system_family:
		dmi_info['DmiSystemFamily'] = "Not Specified"
	else:
		dmi_info['DmiSystemFamily'] = system_family

	# Create a new UUID
	newuuid = str(uuid.uuid4())
	dmi_info['DmiSystemUuid'] = newuuid.upper()
	# Create a new system serial number
	dmi_info['DmiSystemSerial'] = "string:"+(serial_randomize(0, len(system_serial)))

	for v in dmidecode.chassis().values():
		dmi_info['DmiChassisVendor'] = v['data']['Manufacturer']
		chassi_serial = v['data']['Serial Number']
		dmi_info['DmiChassisVersion'] = v['data']['Version']
		dmi_info['DmiChassisType'] = v['data']['Type']

	# Based on the list from http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.0.0.pdf
	chassi_dict = {'Other': 1, 'Unknown': 2, 'Desktop': 3, 'Low Profile Desktop': 4, 'Pizza Box': 5, 'Mini Tower': 6,
				   'Tower': 7, 'Portable': 8, 'Laptop': 9, 'Notebook': 10, 'Hand Held': 11, 'Docking Station': 12,
				   'All in One': 13, 'Sub Notebook': 14, 'Space-saving': 15, 'Lunch Box': 16, 'Main Server Chassis': 17,
				   'Expansion Chassis': 18, 'SubChassis': 19, 'Bus Expansion Chassis': 20, 'Peripheral Chassis': 21}
	dmi_info['DmiChassisType'] = str(chassi_dict.get(dmi_info['DmiChassisType']))
	# python-dmidecode does not reveal all values .. this is plan B
	chassi = commands.getoutput("dmidecode -t3")
	try:
		dmi_info['DmiChassisAssetTag'] = re.search("Asset Tag: ([0-9A-Za-z ]*)", chassi).group(1)
	except:
		dmi_info['DmiChassisAssetTag'] = '** No value to retrieve **'

	# Create a new chassi serial number, added string to make it be taken as a string even if it's a number
	dmi_info['DmiChassisSerial'] = "string:"+str(serial_randomize(0, len(chassi_serial)))

	for v in dmidecode.processor().values():
		dmi_info['DmiProcVersion'] = v['data']['Version']
		dmi_info['DmiProcManufacturer'] = v['data']['Manufacturer']['Vendor']
	# OEM strings
	try:
		for v in dmidecode.type(11).values():
			oem_ver = v['data']['Strings']['3']
			oem_rev = v['data']['Strings']['2']
	except:
		pass
	try:
		dmi_info['DmiOEMVBoxVer'] = oem_ver
		dmi_info['DmiOEMVBoxRev'] = oem_rev
	except:
		dmi_info['DmiOEMVBoxVer'] = '** No value to retrieve **'
		dmi_info['DmiOEMVBoxRev'] = '** No value to retrieve **'

	# Write all data collected so far to file
	file_name="vboxmods-"+vm_name.replace(' ','_')+".sh"

	logfile = file(path_logs+'/'+file_name, 'w+')
	logfile.write('# Generated on: ' + time.strftime("%H:%M:%S") + '\n')

	for k, v in sorted(dmi_info.iteritems()):
		if '** No value to retrieve **' in v:
			logfile.write('# VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/pcbios/0/Config/' + k + '\t' + v + '\n')
		else:
			logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/pcbios/0/Config/' + k + '\t\'' + v + '\'\n')
	# Disk information
	disk_dmi = {}
	try:
		if os.path.exists("/dev/sda"):
			# Disk serial
			disk_serial = commands.getoutput(
				"hdparm -i /dev/sda | grep -o 'SerialNo=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'")
			# To avoid exceding 20 bytes serials
			if len(disk_serial)>20:
				disk_dmi['SerialNumber'] = (serial_randomize(0, 20))
			else:
				disk_dmi['SerialNumber'] = (serial_randomize(0, len(disk_serial)))
			# Check for HP Legacy RAID
		elif os.path.exists("/dev/cciss/c0d0"):
			# Needs smartctl to be able to get the correct information
			if os.path.exists("/usr/sbin/smartctl"):
				hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
				disk_serial = re.search("Serial number:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
				# To avoid exceding 20 bytes serials
				if len(disk_serial)>20:
					disk_dmi['SerialNumber'] = (serial_randomize(0, 20))
				else:
					disk_dmi['SerialNumber'] = (serial_randomize(0, len(disk_serial)))
			else:
				print bcolors.WARNING+"Install smartmontools: apt-get install smartmontools"+bcolors.ENDC
	except OSError:
		print "Haz RAID?"
		print commands.getoutput("lspci | grep -i raid")

	# Disk firmeware rev
	try:
		if os.path.exists("/dev/sda"):
			disk_fwrev = commands.getoutput(
				"hdparm -i /dev/sda | grep -o 'FwRev=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'")
			disk_dmi['FirmwareRevision'] = disk_fwrev
			if len(disk_dmi['FirmwareRevision'])<8:
				disk_dmi['FirmwareRevision']=disk_dmi['FirmwareRevision'][:8]
		elif os.path.exists("/dev/cciss/c0d0"):
			# Needs smartctl to be able to get the correct information
			if os.path.exists("/usr/sbin/smartctl"):
				hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
				disk_dmi['FirmwareRevision'] = re.search("Revision:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
				if len(disk_dmi['FirmwareRevision'])<8:
					disk_dmi['FirmwareRevision']=disk_dmi['FirmwareRevision'][:8]
			else:
				print "Install smartmontools: apt-get install smartmontools"
	except OSError:
		print "Haz RAID?"
		print commands.getoutput("lspci | grep -i raid")

	# Disk Model number
	try:
		if os.path.exists("/dev/sda"):
			disk_modelno = commands.getoutput(
				"hdparm -i /dev/sda | grep -o 'Model=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'")
			disk_dmi['ModelNumber'] = disk_modelno
		elif os.path.exists("/dev/cciss/c0d0"):
			# Needs smartctl to be able to get the correct information
			if os.path.exists("/usr/sbin/smartctl"):
				hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
				disk_dmi['ModelNumber'] = re.search("Product:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
			else:
				print "Install smartmontools: apt-get install smartmontools"
	except OSError:
		print "Haz RAID?"
		print commands.getoutput("lspci | grep -i raid")

	# Write more things to file
	for k, v in disk_dmi.iteritems():
		if '** No value to retrieve **' in v:
			logfile.write('# VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/piix3ide/0/Config/PrimaryMaster/' + k + '\t' + v + '\n')
		else:
			logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/piix3ide/0/Config/PrimaryMaster/' + k + '\t\'' + v + '\'\n')

	# CD-ROM information
	cdrom_dmi = {}
	if os.path.islink('/dev/cdrom'):
		# CD-ROM serial
		cdrom_serial = commands.getoutput(
			"hdparm -i /dev/cdrom | grep -o 'SerialNo=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'")
		if cdrom_serial:
			cdrom_dmi['ATAPISerialNumber'] = (serial_randomize(0, len(cdrom_serial)))
		else:
			cdrom_dmi['ATAPISerialNumber'] = "** No value to retrieve **"

		# CD-ROM firmeware rev
		cdrom_fwrev = commands.getoutput("cd-drive | grep Revision | grep  ':' | awk {' print $3 \" \" $4'}")
		cdrom_dmi['ATAPIRevision'] = cdrom_fwrev.replace(" ", "")

		# CD-ROM Model numberA-Za-z0-9_\+\/ .\"-
		cdrom_modelno = commands.getoutput("cd-drive | grep Model | grep  ':' | awk {' print $3 \" \" $4'}")
		cdrom_dmi['ATAPIProductId'] = cdrom_modelno

		# CD-ROM Vendor
		cdrom_vendor = commands.getoutput("cd-drive | grep Vendor | grep  ':' | awk {' print $3 '}")
		cdrom_dmi['ATAPIVendorId'] = cdrom_vendor
	else:
		logfile.write('# No CD-ROM detected: ** No values to retrieve **\n')

	# And some more
	for k, v in cdrom_dmi.iteritems():
		if '** No value to retrieve **' in v:
			logfile.write('# VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/piix3ide/0/Config/SecondaryMaster/' + k + '\t' + v + '\n')
		else:
			logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/piix3ide/0/Config/SecondaryMaster/' + k + '\t\'' + v + '\'\n')

	# Get the DSDT image
	#os.system("dd if=/sys/firmware/acpi/tables/DSDT of=DSDT.bin >/dev/null 2>&1")
	# Write to file
	# Da un error de que la tabla ACPI es mayor de 64KB, aunque lo comente, si luego ejecuto el batch dentro del Guest, pasa las pruebas
	#logfile.write('VBoxManage setextradata '+vm_name+' VBoxInternal/Devices/acpi/0/Config/CustomTable\t\'' + os.getcwd() + '/DSDT.bin\'\n')

	acpi_misc = commands.getoutput('acpidump -s | grep DSDT | grep -o "\(([A-Za-z0-9].*)\)" | tr -d "()"')
	acpi_list = acpi_misc.split(' ')
	acpi_list = filter(None, acpi_list)

	logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/acpi/0/Config/AcpiOemId\t\'' + acpi_list[1] + '\'\n')
	logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/acpi/0/Config/AcpiCreatorId\t\'' + acpi_list[4] + '\'\n')
	logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/acpi/0/Config/AcpiCreatorRev\t\'' + acpi_list[5] + '\'\n')

	# Randomize MAC address, based on onboard interface MAC
	mac_seed = ':'.join(re.findall('..', '%012x' % uuid.getnode()))[0:9]
	big_mac = mac_seed + "%02x:%02x:%02x" % (
		random.randint(0, 255),
		random.randint(0, 255),
		random.randint(0, 255),
	)
	le_big_mac = re.sub(':', '', big_mac)

	# The last thing!
	logfile.write('VBoxManage modifyvm "'+vm_name+'" --macaddress1\t' + le_big_mac +'\n')
	# Done!
	logfile.close()

	print '	Finished: A template shell script has been created named:', file_name
	print bcolors.OKGREEN+'\n [*]'+bcolors.ENDC+' Creating guest based modification file (to be run inside the guest)'

	# Write all data to file
	file_name2="vboxmods-"+vm_name.replace(' ','_')+".bat"
	logfile = file('/srv/ftp/CopyThisOne!/' +file_name2, 'w+')

	manu = acpi_list[1]

	# DSDT
	logfile.write('@reg copy HKLM\HARDWARE\ACPI\DSDT\VBOX__ HKLM\HARDWARE\ACPI\DSDT\\' + manu + ' /s /f\n\n')
	logfile.write('@reg delete HKLM\HARDWARE\ACPI\DSDT\VBOX__ /f\n\n')

	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\VBOXBIOS HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\\' + acpi_list[2] + '___' + ' /s /f\n\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\VBOXBIOS /f\n\n')

	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\\' + acpi_list[2] + '___\\00000002 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\\' + acpi_list[2] + '___\\' + acpi_list[3] + ' /s /f\n\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\\' + acpi_list[2] + '___\\00000002 /f\n')

	# FADT
	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\VBOXFACP HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\\' + acpi_list[2] + '___  /s /f\n\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\VBOXFACP /f\n')
	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\\' + acpi_list[2] + '___\\00000001 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\\' + acpi_list[2] + '___\\' + acpi_list[3] + ' /s /f\n\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\\' + acpi_list[2] + '___\\00000001 /f\n\n')

	# RSDT
	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\VBOXRSDT HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\\' + acpi_list[2] + '___  /s /f\r\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\VBOXRSDT /f\r\n')
	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\\' + acpi_list[2] + '___\\00000001 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\\' + acpi_list[2] + '___\\' + acpi_list[3] + ' /s /f\r\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\\' + acpi_list[2] + '___\\00000001 /f\r\n')


	# SystemBiosVersion - TODO: get real values
	logfile.write('@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v SystemBiosVersion /t REG_MULTI_SZ /d "' + acpi_list[1] + ' - ' + acpi_list[0] + '" /f\n\n')
	# VideoBiosVersion - TODO: get real values
	logfile.write('@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v VideoBiosVersion /t REG_MULTI_SZ /d "' + acpi_list[0] + '" /f\n')
	# SystemBiosDate
	d_month, d_day, d_year = dmi_info['DmiBIOSReleaseDate'].split('/')

	if len(d_year) > 2:
		d_year = d_year[:2]

	logfile.write('@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v SystemBiosDate /t REG_MULTI_SZ /d "' + d_month + '/' + d_day + '/' + d_year + '" /f\n')


	# Prevent WMI identification
	logfile.write('@reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\PlugPlay /v Start /t REG_MULTI_SZ /d "4" /f\r\n')
	#The system have to be rebooted for this to work, don't know why

	#  Disables FW
	logfile.write('netsh firewall set opmode disable\n')
	# Disables windows updates
	logfile.write('@reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v AUOptions /t REG_DWORD /d 1 /f\n')
	# Change the IP and DNS
	shortScript='''
		@echo off

		set _enabled=Habilitado
		set _dedicated=Dedicado

		for /f "tokens=1,2,3*" %%i in ('netsh int show interface') do (
			if %%i equ %_enabled% (
				if %%j equ %_dedicated% (
					netsh int ip set address "%%k %%l" static '''+guest_ip+''' 255.255.255.0 '''+host_ip+''' 1
					netsh int ip set dns "%%k %%l" static '''+guest_primary_dns+'''
				 )
			)
		)
		ipconfig /flushdns

		:EOF'''
	logfile.write(shortScript+'\n')

	logfile.close()
	print '	Finished: A Windows batch file has been created named:', file_name2
	
	return
Exemplo n.º 50
0
def run(options, steps):
    if not steps:
        steps = ["fw-updates", "oob-config", "intake", "reboot"]

    try:
        system = dmidecode.system()
        system_manufacturer = [
            v for k, v in system.items() if 'Manufacturer' in v['data']
        ][0]['data']['Manufacturer']
        if system_manufacturer.startswith("HP"):
            system_manufacturer = "HP"
            model = [
                v for k, v in system.items() if 'Product Name' in v['data']
            ][0]['data']['Product Name'].strip()
            asset_tag = [
                v for k, v in system.items() if 'Serial Number' in v['data']
            ][0]['data']['Serial Number'].strip()
        elif system_manufacturer.startswith("Dell"):
            system_manufacturer = "Dell"
            model = [
                v for k, v in system.items() if 'Product Name' in v['data']
            ][0]['data']['Product Name'].strip()
            asset_tag = [
                v for k, v in system.items() if 'Serial Number' in v['data']
            ][0]['data']['Serial Number'].strip()
        elif system_manufacturer.startswith("Supermicro"):
            system_manufacturer = "Supermicro"
            baseboard = dmidecode.baseboard()
            model = [
                v for k, v in system.items() if 'Product Name' in v['data']
            ][0]['data']['Product Name'].strip()
            if model in ('Super Server', 'To be filled by O.E.M.'):
                model = [
                    v for k, v in baseboard.items()
                    if 'Product Name' in v['data']
                ][0]['data']['Product Name'].strip()
            asset_tag = [
                v for k, v in baseboard.items() if 'Serial Number' in v['data']
            ][0]['data']['Serial Number'].strip()
        else:
            raise Exception("Unknown")
    except:
        system_manufacturer = "Unknown"
        model = "Unknown"
        asset_tag = "Unknown"

    security_qs = {}
    if options.hmac:
        security_qs['hmac'] = options.hmac
    if options.nonce:
        security_qs['nonce'] = options.nonce

    while True:
        try:
            response = requests.get("%sconfig/%s" % (options.url, asset_tag),
                                    params=security_qs,
                                    verify=False,
                                    headers={"Accept": "application/json"})
        except:
            response = None
        if response is not None and response.status_code == 200:
            break
        else:
            time.sleep(5)

    configuration = response.text
    configuration_file = "/tmp/sot.conf"
    with open(configuration_file, 'w') as f:
        f.write(configuration)

    for step in steps:
        # Special steps implemented here
        data = None
        if step == 'reboot':
            subprocess.call(["/sbin/shutdown", "-r", "+1"])
            data = {'msg': 'rebooting'}
            ret = 1
        elif step == 'poweroff':
            subprocess.call(["/sbin/shutdown", "-h", "+1"])
            data = {'msg': 'powering off'}
            ret = 1
        else:
            p = subprocess.Popen([
                os.path.join(options.path, step), system_manufacturer, model,
                asset_tag, configuration_file
            ],
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            stdout, stderr = p.communicate()
            ret = p.returncode
            try:
                data = json.loads(stdout)
            except:
                pass
        report = {
            'step': step,
            'data': data,
            'returncode': p.returncode,
            'stderr': stderr
        }
        response = requests.post("%sintake/%s" % (options.url, asset_tag),
                                 data=json.dumps(report),
                                 params=security_qs,
                                 verify=False,
                                 headers={
                                     "Content-Type": "application/json",
                                     "Accept": "application/json"
                                 })
        if ret != 0 or data is None or (
                'failed' in data
                and data['failed']) or response.status_code not in [200, 201]:
            sys.stderr.write(
                "Failed to run step %s, report %r, response code is %s\n" %
                (step, report, response.status_code))
            break