def reg_connect_registry(machine, hive): """ With-statement handler. Use as: with reg_connect_registry(machine, hive) as reghandle: ... """ reghandle = win32api.RegConnectRegistry(machine, hive) yield reghandle
def getuuids(self): """ for each UUID in the registry, find the file, and if it's unique, load it requires win32api HKLM\Software\Microsoft\Internet Explorer\ActiveX Compatability\ If they have the 0x400 bit set, they're "killed" """ uuidsdone = {} reg = win32api.RegConnectRegistry(None, win32con.HKEY_CLASSES_ROOT) key = win32api.RegOpenKeyEx(reg, "CLSID") subkey = "Hi" i = 1 while subkey != "": try: subkey = win32api.RegEnumKey(key, i) #print "Subkey=%s"%subkey except pywintypes.error: #end of registry just throws a lame exception subkey = "" continue try: new_subkey = win32api.RegOpenKeyEx(key, subkey) print "Got new subkey for %s" % subkey subkey2 = win32api.RegOpenKeyEx(new_subkey, "InprocServer32") print "Got InprocServer subkey" value = win32api.RegEnumValue(subkey2, 0) print "Value = %s" % (value, ) dllname = value[1].lower() print "Dllname=%s" % dllname if dllname.count("exe") or dllname.count("dll"): print "Clearing" self.clear() print "Doing file" self.dofile(dllname) print "Doing all imports" self.doallimports() else: print "Not a dll or exe!" except pywintypes.error: #import traceback #traceback.print_exc(file=sys.stdout) pass #print "No InprocServer subkey..." i += 1 print "Done with getuuids" print "Done DLLS: %s" % (self.imports, ) sys.exit(1)
def reg2dict(key, computer=None, hive=win32con.HKEY_LOCAL_MACHINE, deep=True): ''' Extract contents of a registry key into a dictionary tree. key - registry key (e.g r"SOFTWARE\Microsoft\Windows NT"). Should not include hive prefix like HKEY_LOCAL_MACHINE computer = HOSTNAME or IPADDRESS of the remote computer. Defaults to current computer. hive - defaults to win32con.HKEY_LOCAL_MACHINE deep - If true, registry is walked recursively to generate dictionary tree. False - returns values from top level key only. Default is True. ''' if not computer: computer = platform.node() hive_hdl = win32api.RegConnectRegistry("\\\\" + computer, hive) key_hdl = win32api.RegOpenKeyEx(hive_hdl, key) return _reg2dict_for_key(key_hdl, deep)
def getSoftwareList(self): try: hCounter = 0 hAttCounter = 0 # connecting to the base hHandle = win32api.RegConnectRegistry(None, win32con.HKEY_LOCAL_MACHINE) # getting the machine name and domain name hCompName = win32api.GetComputerName() hDomainName = win32api.GetDomainName() # opening the sub key to get the list of Softwares installed hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE, self.CONST_SW_SUBKEY, 0, win32con.KEY_ALL_ACCESS) # get the total no. of sub keys hNoOfSubNodes = win32api.RegQueryInfoKey(hHandle) # delete the entire data and insert it again #deleteMachineSW(hCompName,hDomainName) # browsing each sub Key which can be Applications installed while hCounter < hNoOfSubNodes[0]: hAppName = win32api.RegEnumKey(hHandle, hCounter) hPath = self.CONST_SW_SUBKEY + "\\" + hAppName # initialising hAttCounter hAttCounter = 0 hOpenApp = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE, hPath, 0, win32con.KEY_ALL_ACCESS) # [1] will give the no. of attributes in this sub key hKeyCount = win32api.RegQueryInfoKey(hOpenApp) hMaxKeyCount = hKeyCount[1] hSWName = "" hSWVersion = "" while hAttCounter < hMaxKeyCount: hData = win32api.RegEnumValue(hOpenApp, hAttCounter) if hData[0] == "DisplayName": hSWName = hData[1] self.preparefile("SW Name", hSWName) elif hData[0] == "DisplayVersion": hSWVersion = hData[1] self.preparefile("SW Version", hSWVersion) hAttCounter = hAttCounter + 1 #if (hSWName !=""): #insertMachineSW(hCompName,hDomainName,hSWName,hSWVersion) hCounter = hCounter + 1 except: self.preparefile("Exception", "In exception in getSoftwareList")
def ModifyReg(key, keyPath, valueName, valueType, value): try: ''' RegConnectRegistry: computerName: string(If None, the local computer is used) key: int(May be win32con.HKEY_LOCAL_MACHINE...) ''' keyHandle = win32api.RegConnectRegistry(None, key) ''' RegOpenKeyEx: key: PyHKEY/int subKey: string reserved = 0: int(Reserved. Must be zero.) sam = KEY_READ: int(If you want to set the value later, you must open the key with KEY_SET_VALUE) ''' subkeyHandle = win32api.RegOpenKeyEx(keyHandle, keyPath) ''' RegQueryValueEx: key: PyHKEY/int valueName: The name of the value to query ''' (currValue, type) = win32api.RegQueryValueEx(subkeyHandle, valueName) if (currValue == value): print('PASS: Check reg value: %s' % valueName) return 1 else: print('INFO: The %s is not the same as %s' % (valueName, value)) print('INFO: Try to set %s as %s' %(valueName, value)) subkeyHandle = win32api.RegOpenKeyEx(keyHandle, keyPath, 0, win32con.KEY_SET_VALUE) ''' RegSetValueEx: key: PyHKEY/int valueName: string(The name of the value to set) reserved: any(Zero will always be passed to the API function) type: int(REG_DWORD, REG_SZ ...) value: registry data ''' win32api.RegSetValueEx(subkeyHandle, valueName, 0, valueType, value) except: print('FAIL: ModifyReg %s. Exception happened. Exception happened when accessing registry key under %s.' % (valueName, keyPath)) return 0 print('SUCCESS: ModifyReg %s value under %s' % (valueName, keyPath)) return 1
def _modify_access(self, key, keypath, valuename, valuetype, value): import win32con import win32api try: keyhandle = win32api.RegConnectRegistry(None, key) subkeyhandle = win32api.RegOpenKeyEx(keyhandle, keypath, 0, win32con.KEY_READ) curvalue, type = win32api.RegQueryValueEx(subkeyhandle, valuename) if curvalue != value: win32api.RegCloseKey(subkeyhandle) subkeyhandle = win32api.RegOpenKeyEx(keyhandle, keypath, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(subkeyhandle, valuename, 0, valuetype, value) win32api.RegCloseKey(subkeyhandle) win32api.RegCloseKey(keyhandle) return True except: return False
def _getPath(): """Retrieves 7-Zip install path and binary from Windows Registry. This way, we do not rely on PATH containing 7-Zip. """ path = None if isWindows(): import win32api, win32con for key in (win32con.HKEY_LOCAL_MACHINE, win32con.HKEY_CURRENT_USER): try: key = win32api.RegConnectRegistry(None, key) key = win32api.RegOpenKeyEx(key, r"SOFTWARE\7-Zip") path, dtype = win32api.RegQueryValueEx(key, "Path") path = os.path.abspath(os.path.join(path, "7z.exe")) except: pass else: p = subprocess.Popen(["which", "7z"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() path = out.strip() return path
def __init__(self, hKey, path=None, machine=None): self.access = Con.KEY_ALL_ACCESS if isinstance(hKey, pywintypes.HANDLEType): if path is None: self.hKey = hKey self.path = None else: self.hKey = Api.RegOpenKeyEx(hKey, path, 0, self.access) self.path = path self.machine = None else: if machine is None: self.hKey = Api.RegOpenKeyEx(hKey, path, 0, self.access) self.path = path else: if not machine.startswith("\\\\"): machine = "\\\\%s" % machine hKey = Api.RegConnectRegistry(machine, hKey) if path is None: self.hKey = hKey else: self.hKey = Api.RegOpenKeyEx(hKey, path, 0, self.access) self.path = path self.machine = machine
def get_font_detail(self, font_id): assert font_id is not None and len(font_id.strip()) > 0 # while not self.__font_detail_cache_lock(False): # logging.warn("font cache lock acquire() has been blocked" font_id = font_id.strip().lower() if font_id in self.__font_detail_cache: #logging.debug("Font cache hit for \"%s\"" % font_id) return self.__font_detail_cache[font_id] font_detail = None try: regkey = win32api.RegOpenKeyEx( # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy win32api.RegConnectRegistry( None, win32con.HKEY_LOCAL_MACHINE ), # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy FONT_LIST_REG_KEY) i = 0 try: RegEnumValue = win32api.RegEnumValue # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy # Optimization _splitext = os.path.splitext _pathjoin = os.path.join while True: font_name, font_file, _ = RegEnumValue(regkey, i) i += 1 _, ext = _splitext(font_file) if ext.lower() != ".ttf": continue font_path = _pathjoin(FONT_DIR, font_file) m = match_bare_font_name(font_name) if m: font_name = m.group(1) if simplify_font_name(font_id) == simplify_font_name(font_name).lower() or \ simplify_font_name(font_id) == simplify_font_name(_splitext(font_file)[0].lower()): font_detail = FontDetail([font_name], font_path, font_file) self.__font_detail_cache[font_id] = font_detail break except Exception as e: # Eroor 259: No more data is available, thrown by reg.EnumValue if not hasattr(e, "winerror") or e.winerror != 259: raise # Make a dent in the cache even if we did not find anything self.__font_detail_cache[font_id] = None finally: if regkey: with suppress(Exception): win32api.RegCloseKey( regkey ) # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy """ font_name2 = self._get_font_name_from_file(font_path) if font_name2 and font_name != font_name2: font_info['names'].append(font_name2) """ except Exception as e: logging.error(e) return font_detail
def getSysInfo(self): try: hCounter = 0 hProcessorName = "" # connecting to the base hHandle = win32api.RegConnectRegistry(None, self.HKEY_LOCAL_MACHINE) # opening the sub key to get the processor name print "debug1" hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE, self.CONST_PROC_SUBKEY, 0, win32con.KEY_ALL_ACCESS) hNoOfKeys = win32api.RegQueryInfoKey(hHandle)[1] while hCounter < hNoOfKeys: hData = win32api.RegEnumValue(hHandle, hCounter) if hData[0] == "Identifier": hProcessorName = hData[1] hCounter = hCounter + 1 if hProcessorName == "": hProcessorName = "Processor Name Cannot be determined" self.preparefile("Processor Name", hProcessorName) hCompName = win32api.GetComputerName() self.preparefile("Computer Name", hCompName) hDomainName = win32api.GetDomainName() self.preparefile("Domain Name", hDomainName) hUserName = win32api.GetUserName() self.preparefile("User Name", hUserName) # getting OS Details hCounter = 0 # opening the sub key to get the processor name hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE, self.CONST_OS_SUBKEY, 0, win32con.KEY_ALL_ACCESS) hNoOfKeys = win32api.RegQueryInfoKey(hHandle)[1] hOSVersion = "" hOSName = "" while hCounter < hNoOfKeys: hData = win32api.RegEnumValue(hHandle, hCounter) if hData[0] == "ProductName": hOSName = hData[1] self.preparefile("OS Name", hOSName) break hCounter = hCounter + 1 if hOSName == "": self.preparefile( "OS Name", "OS Name could not be read from the registry") hCounter = 0 while hCounter < hNoOfKeys: hData = win32api.RegEnumValue(hHandle, hCounter) if hData[0] == "CSDVersion": hOSVersion = hData[1] self.preparefile("OS Version", hOSVersion) break hCounter = hCounter + 1 if hOSVersion == "": self.preparefile( "OS Version", "OS Version could not be read from the registry") # inserting master data #insertMachineMaster(hCompName,hDomainName,hOSName,hOSVersion,hProcessorName) except: self.preparefile("Exception", "in Exception in getSysDetails")