def test_CreateKey(self): from winreg import CreateKey, QueryInfoKey key = CreateKey(self.root_key, self.test_key_name) sub_key = CreateKey(key, "sub_key") nkeys, nvalues, since_mod = QueryInfoKey(key) assert nkeys == 1 nkeys, nvalues, since_mod = QueryInfoKey(sub_key) assert nkeys == 0
def test_CreateKeyEx(self): from winreg import CreateKeyEx, QueryInfoKey from winreg import KEY_ALL_ACCESS, KEY_READ key = CreateKeyEx(self.root_key, self.test_key_name, 0, KEY_ALL_ACCESS) sub_key = CreateKeyEx(key, "sub_key", 0, KEY_READ) nkeys, nvalues, since_mod = QueryInfoKey(key) assert nkeys == 1 nkeys, nvalues, since_mod = QueryInfoKey(sub_key) assert nkeys == 0
def find_bluestacks4_hyperv(serial): """ Find dynamic serial of Bluestacks4 Hyper-v Beta. Args: serial (str): 'bluestacks4-hyperv', 'bluestacks4-hyperv-2' for multi instance, and so on. Returns: str: 127.0.0.1:{port} """ from winreg import ConnectRegistry, OpenKey, QueryInfoKey, EnumValue, CloseKey, HKEY_LOCAL_MACHINE logger.info("Use Bluestacks4 Hyper-v Beta") if serial == "bluestacks4-hyperv": folder_name = "Android" else: folder_name = f"Android_{serial[19:]}" logger.info("Reading Realtime adb port") reg_root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) sub_dir = f"SOFTWARE\\BlueStacks_bgp64_hyperv\\Guests\\{folder_name}\\Config" bs_keys = OpenKey(reg_root, sub_dir) bs_keys_count = QueryInfoKey(bs_keys)[1] for i in range(bs_keys_count): key_name, key_value, key_type = EnumValue(bs_keys, i) if key_name == "BstAdbPort": logger.info(f"New adb port: {key_value}") serial = f"127.0.0.1:{key_value}" break CloseKey(bs_keys) CloseKey(reg_root) return serial
def enum_key(hive, subkey: str): with OpenKey(hive, subkey, 0, KEY_ALL_ACCESS) as key: num_of_values = QueryInfoKey(key)[1] for i in range(num_of_values): values = EnumValue(key, i) if values[0] == "LangID": continue print(*values[:-1], sep="\t")
def read_key( self, name: str, key_wow64_32key: bool = False, ) -> RegKey: handle = self._get_handler(name, KEY_READ, key_wow64_32key) keys_num, values_num, modify = QueryInfoKey(handle) modify_at = datetime(1601, 1, 1) + timedelta(microseconds=modify / 10) keys = list() entries = list() for key_i in range(0, keys_num): keys.append(EnumKey(handle, key_i)) for key_i in range(0, values_num): entry_name, value, raw_type = EnumValue(handle, key_i) entries.append( RegEntry( reg_key=name, name=entry_name, value=value, type=WinregType(raw_type), host=self.host, )) return RegKey( name=name, reg_keys=keys, entries=entries, modify_at=modify_at, )
def type(self): """Get resource type. NOTE: this winreg-based method enumerates all resources which makes it a bit slower. But, IT WORKS. >>> import mscluster >>> C = mscluster.Cluster() >>> while (True): ... Cr = next(C.resources) ... if Cr == 'AG-LABC': ... R = C.openResource(Cr) ... Rtype = R.type ... break >>> Rtype 'SQL Server Availability Group' """ with OpenKey(HKEY_LOCAL_MACHINE, "Cluster\Resources") as rsKey: (rskeys, rsvals, rsmod) = QueryInfoKey(rsKey) for n in range(rskeys): rid = EnumKey(rsKey, n) with OpenKey(rsKey, rid) as rKey: (rname, rname_t) = QueryValueEx(rKey, "Name") if rname == self.name: (rtype, rtype_t) = QueryValueEx(rKey, "Type") return rtype raise RuntimeError("Unable to find resource type for [{}]".format( self.name))
def _users(self): r""" (Windows) This function checks the registry key: ``SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList`` for user sids. If a new account is created, the alert will be triggered after the system is rebooted and is updated to reflect the creation of the account. (Linux) Open the etc/passwd file and extracts all the user's. If a new user is found within this file or if a service account shell has been updated to an interactive logon shell, an alert will be triggered """ target_key = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" allowed_users = tuple(map(lambda s: s.strip(), self.config["users"]["allow"].split("|"))) if self.system == "Windows": with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hklm: with OpenKey(hklm, target_key, 0, KEY_ALL_ACCESS) as profile_list: subkeys = QueryInfoKey(profile_list)[0] for i in range(subkeys): subkey = EnumKey(profile_list, i) if search(r"^S-\d-\d+-(\d+-){1,14}\d+$", subkey): with OpenKey(hklm, f"{target_key}\\{subkey}", 0, KEY_ALL_ACCESS) as user_key: user = QueryValueEx(user_key, r"ProfileImagePath")[0].split("\\")[-1] if user not in allowed_users: message = f"Host: {self.hostname}\nTime: {datetime.now()}\nAlert: c4N4Re has detected a interactive new user: {user}. " \ f"If you have not created a new user or have not changed the shell " \ f"for a service account, then your system might be compromised!" self.__send_alert( self.config["users"]["subject"], message) self.num_of_alerts += 1 else: linux_shells = ( "bash", # GNU Bourne-Again Shell "sh", # Bourne Shell "ksh", # Korn Shell "zsh", # Z Shell "csh" # C Shell ) interactive_users = [] allowed_users = tuple(map(lambda s: s.strip(), self.config["users"]["allow"].split('|'))) with open("/etc/passwd") as passwd: for entry in passwd: entry = entry.strip().split(":") user, shell = entry[0], entry[-1].split('/')[-1] if shell in linux_shells: interactive_users.append(user) for interactive_user in interactive_users: if interactive_user not in allowed_users: message = f"Host: {self.hostname}\nTime: {datetime.now()}\nAlert: c4N4Re has detected " \ f"a new interactive user: {interactive_user}. " \ f"If you have not created a new user or have not changed the shell " \ f"for a service account, then your system might be compromised!" self.__send_alert( self.config["users"]["subject"], message) self.num_of_alerts += 1
def __win32_finddll(): from winreg import OpenKey, CloseKey, EnumKey, QueryValueEx, \ QueryInfoKey, HKEY_LOCAL_MACHINE from distutils.version import LooseVersion import os dlls = [] # Look up different variants of Ghostscript and take the highest # version for which the DLL is to be found in the filesystem. for key_name in ('AFPL Ghostscript', 'Aladdin Ghostscript', 'GPL Ghostscript', 'GNU Ghostscript'): try: k1 = OpenKey(HKEY_LOCAL_MACHINE, "Software\\%s" % key_name) for num in range(0, QueryInfoKey(k1)[0]): version = EnumKey(k1, num) try: k2 = OpenKey(k1, version) dll_path = QueryValueEx(k2, 'GS_DLL')[0] CloseKey(k2) if os.path.exists(dll_path): dlls.append((LooseVersion(version), dll_path)) except WindowsError: pass CloseKey(k1) except WindowsError: pass if dlls: dlls.sort() return dlls[-1][-1] else: return None
def set_keys(self): baseOfficeKeyPath = r"Software\Microsoft\Office" installedVersions = list() try: officeKey = OpenKey(HKEY_CURRENT_USER, baseOfficeKeyPath, 0, KEY_READ) for currentKey in range(0, QueryInfoKey(officeKey)[0]): isVersion = True officeVersion = EnumKey(officeKey, currentKey) if "." in officeVersion: for intCheck in officeVersion.split("."): if not intCheck.isdigit(): isVersion = False break if isVersion: installedVersions.append(officeVersion) CloseKey(officeKey) except WindowsError: # Office isn't installed at all return for oVersion in installedVersions: key = CreateKeyEx( HKEY_CURRENT_USER, r"{0}\{1}\Publisher\Security".format(baseOfficeKeyPath, oVersion), 0, KEY_SET_VALUE) SetValueEx(key, "VBAWarnings", 0, REG_DWORD, 1) SetValueEx(key, "AccessVBOM", 0, REG_DWORD, 1) SetValueEx(key, "ExtensionHardening", 0, REG_DWORD, 0) CloseKey(key)
def getLatestKey(hKey): curaList = [] for i in range(0, QueryInfoKey(hKey)[0]): curaList.append(EnumKey(hKey, i)) fList = [k for k in curaList if 'Ultimaker Cura' in k] fList.sort() return fList[-1]
def list_ports(): from winreg import OpenKey, EnumValue, QueryInfoKey, HKEY_LOCAL_MACHINE with OpenKey(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM") as comm: count = QueryInfoKey(comm)[1] for i in range(count): name, value, _ = EnumValue(comm, i) print(name, value)
def collect_registry(hkey, root_key): things_to_remove = [] with OpenKey(hkey, root_key) as depKey: dep_key_count = QueryInfoKey(depKey)[0] print('Found {0} keys'.format(dep_key_count)) for i in range(0, dep_key_count): dep_key_str = EnumKey(depKey, i) if dep_key_str[0] == '{': with OpenKey(depKey, dep_key_str) as targetKey: target_key_count = QueryInfoKey(targetKey)[1] for j in range(0, target_key_count): key_value = EnumValue(targetKey, j) if key_value[0] == 'DisplayName': installer_name = key_value[1] if check_name(installer_name): things_to_remove.append( (installer_name, dep_key_str)) return things_to_remove
def readValues(hkey, regPath): if not pathExists(hkey, regPath): return -1 reg = OpenKey(hkey, regPath) values = {} noOfValues = QueryInfoKey(reg)[1] for i in range(0, noOfValues): values[EnumValue(reg, i)[0]] = EnumValue(reg, i)[1] CloseKey(reg) return values
def subkeys(hkey=HKEY_CURRENT_USER, path='', accum=''): with suppress(WindowsError), OpenKey(hkey, path) as k: nsubkeys, nvalues, _ = QueryInfoKey(k) # for i in range(nvalues): # yield winreg.EnumValue(k, i) for i in range(nsubkeys): sub_key = EnumKey(k, i) fullpath = accum + '\\' + sub_key yield fullpath yield from subkeys(k, sub_key, fullpath)
def readSubKeys(hkey, regPath): if not pathExists(hkey, regPath): return -1 reg = OpenKey(hkey, regPath) subKeys = [] noOfSubkeys = QueryInfoKey(reg)[0] for i in range(0, noOfSubkeys): subKeys.append(EnumKey(reg, i)) CloseKey(reg) return subKeys
def modified_datetime(self, path): localPath = path.replace("/", "\\") rootKey = ConnectRegistry(None, HKEY_CURRENT_USER) try: key = OpenKey(rootKey, localPath) subKeyCount, valueCount, lastModified = QueryInfoKey(key) return datetime(1600, 1, 1, tzinfo=timezone.utc) + timedelta( seconds=lastModified * 100e-9) except EnvironmentError: # TODO raise FileNotFoundError if path isn't a value return None
def test_close(self): from winreg import OpenKey, CloseKey, FlushKey, QueryInfoKey key = OpenKey(self.root_key, self.test_key_name) sub_key = OpenKey(key, "sub_key") int_sub_key = int(sub_key) FlushKey(sub_key) CloseKey(sub_key) raises(EnvironmentError, QueryInfoKey, int_sub_key) int_key = int(key) key.Close() raises(EnvironmentError, QueryInfoKey, int_key) key = OpenKey(self.root_key, self.test_key_name) int_key = key.Detach() QueryInfoKey(int_key) # works key.Close() QueryInfoKey(int_key) # still works CloseKey(int_key) raises(EnvironmentError, QueryInfoKey, int_key) # now closed
def delete_key_tree( self, name: str, key_wow64_32key: bool = False, ) -> None: handle = self._get_handler(name, KEY_READ, key_wow64_32key) keys_num, values_num, modify = QueryInfoKey(handle) # pylint: disable=unused-variable for key_i in range(0, keys_num): key = EnumKey(handle, key_i) self.delete_key_tree(f"{name}\\{key}", key_wow64_32key) handle.Close() self.delete_key(name, key_wow64_32key)
def test_exception(self): from winreg import QueryInfoKey import errno try: QueryInfoKey(0) except EnvironmentError as e: assert e.winerror == 6 assert e.errno == errno.EBADF # XXX translations... assert ("invalid" in e.strerror.lower() or "non valide" in e.strerror.lower()) else: assert 0, "Did not raise"
def __get_sub_keys(self, key): partial_key, root_hive = self.__parse_key(key) with ConnectRegistry(None, root_hive) as reg: with OpenKey(reg, partial_key) as key_object: sub_keys_count, values_count, last_modified = QueryInfoKey( key_object) try: for i in range(sub_keys_count): sub_key_name = EnumKey(key_object, i) yield sub_key_name except WindowsError: pass
def test_long_key(self): from winreg import (HKEY_CURRENT_USER, KEY_ALL_ACCESS, CreateKey, SetValue, EnumKey, REG_SZ, QueryInfoKey, OpenKey, DeleteKey) name = 'x' * 256 try: with CreateKey(HKEY_CURRENT_USER, self.test_key_name) as key: SetValue(key, name, REG_SZ, 'x') num_subkeys, num_values, t = QueryInfoKey(key) EnumKey(key, 0) finally: with OpenKey(HKEY_CURRENT_USER, self.test_key_name, 0, KEY_ALL_ACCESS) as key: DeleteKey(key, name) DeleteKey(HKEY_CURRENT_USER, self.test_key_name)
def set_office_params(self): baseOfficeKeyPath = r"Software\Microsoft\Office" installedVersions = [] try: with OpenKey(HKEY_CURRENT_USER, baseOfficeKeyPath, 0, KEY_READ) as officeKey: for currentKey in range(QueryInfoKey(officeKey)[0]): officeVersion = EnumKey(officeKey, currentKey) if "." in officeVersion: isVersion = True for intCheck in officeVersion.split("."): if not intCheck.isdigit(): isVersion = False break if isVersion: installedVersions.append(officeVersion) except WindowsError: # Office isn't installed at all return self._office_helper("Software\\Microsoft\\Office\\Common\\Security", "DisableAllActiveX", REG_DWORD, 0) self._office_helper("Software\\Microsoft\\Office\\Common\\Security", "UFIControls", REG_DWORD, 1) for oVersion in installedVersions: for software in ("Word", "Excel", "PowerPoint", "Publisher", "Outlook"): productPath = rf"{baseOfficeKeyPath}\{oVersion}\{software}" self._office_helper(f"{productPath}\\Common\\General", "ShownOptIn", REG_DWORD, 1) self._office_helper(f"{productPath}\\Security", "VBAWarnings", REG_DWORD, 1) self._office_helper(f"{productPath}\\Security", "AccessVBOM", REG_DWORD, 1) self._office_helper(f"{productPath}\\Security", "DisableDDEServerLaunch", REG_DWORD, 0) self._office_helper(f"{productPath}\\Security", "MarkInternalAsUnsafe", REG_DWORD, 0) self._office_helper(f"{productPath}\\Security\\ProtectedView", "DisableAttachmentsInPV", REG_DWORD, 1) self._office_helper(f"{productPath}\\Security\\ProtectedView", "DisableInternetFilesInPV", REG_DWORD, 1) self._office_helper(f"{productPath}\\Security\\ProtectedView", "DisableUnsafeLocationsInPV", REG_DWORD, 1) # self._office_helper(f"HKEY_CURRENT_USER\\Software\\Policies\\Microsoft\\Office\\{oVersion}\\{software}\\Security", "MarkInternalAsUnsafe", REG_DWORD, 0) self._office_helper(f"{productPath}\\Security", "ExtensionHardening", 0)
def persist(malicious_exe_path: str, target_exe: str, target_reg_keys: list): with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hklm: # create the `Image File Execution Options` subkey with target executable CreateKeyEx(hklm, target_reg_keys[0], 0, KEY_WRITE) # create the `SilentProcessExit` subkey with target executable CreateKeyEx(hklm, target_reg_keys[1], 0, KEY_WRITE) for reg_key in target_reg_keys: with OpenKey(hklm, reg_key, 0, KEY_ALL_ACCESS) as target_key: for _ in range(QueryInfoKey(target_key)[0]): if "Image File Exection" in reg_key: SetValueEx(hklm, "GlobalFlag", 0, REG_DWORD, 512) else: SetValueEx(hklm, "ReportingMode", 0, REG_DWORD, 1) SetValueEx(hklm, "MonitorProcess", 0, REG_SZ, malicious_exe_path) flush_registry_changes()
def find_bluestacks5_hyperv(serial): """ Find dynamic serial of Bluestacks5 Hyper-v. Args: serial (str): 'bluestacks5-hyperv', 'bluestacks5-hyperv-1' for multi instance, and so on. Returns: str: 127.0.0.1:{port} """ from winreg import ConnectRegistry, OpenKey, QueryInfoKey, EnumValue, CloseKey, HKEY_LOCAL_MACHINE logger.info("Use Bluestacks5 Hyper-v") logger.info("Reading Realtime adb port") if serial == "bluestacks5-hyperv": parameter_name = "bst.instance.Nougat64.status.adb_port" else: parameter_name = f"bst.instance.Nougat64_{serial[19:]}.status.adb_port" reg_root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) sub_dir = f"SOFTWARE\\BlueStacks_nxt" bs_keys = OpenKey(reg_root, sub_dir) bs_keys_count = QueryInfoKey(bs_keys)[1] for i in range(bs_keys_count): key_name, key_value, key_type = EnumValue(bs_keys, i) if key_name == "UserDefinedDir": logger.info(f"Configuration file directory: {key_value}") with open(f"{key_value}\\bluestacks.conf", 'r', encoding='utf-8') as f: content = f.read() port = re.findall(rf'{parameter_name}="(.*?)"\n', content, re.S) if len(port) > 0: logger.info(f"Match to dynamic port: {port[0]}") serial = f"127.0.0.1:{port[0]}" else: logger.warning(f"Did not match the result: {serial}.") break CloseKey(bs_keys) CloseKey(reg_root) return serial
def _get_keys(hive: int, key: str, arch: int, open_reg: HKEYType, recursion_level: int, filter_on_names: List[str]): try: if not open_reg: open_reg = ConnectRegistry(None, hive) open_key = OpenKey(open_reg, key, 0, KEY_READ | arch) subkey_count, value_count, _ = QueryInfoKey(open_key) output = {} values = [] for index in range(value_count): name, value, type = EnumValue(open_key, index) if isinstance(filter_on_names, list) and name not in filter_on_names: pass else: values.append({'name': name, 'value': value, 'type': type}) if not values == []: output[''] = values if recursion_level > 0: for subkey_index in range(subkey_count): try: subkey_name = EnumKey(open_key, subkey_index) sub_values = get_keys(hive=0, key=key + '\\' + subkey_name, arch=arch, open_reg=open_reg, recursion_level=recursion_level - 1, filter_on_names=filter_on_names) output[subkey_name] = sub_values except FileNotFoundError: pass return output except (FileNotFoundError, TypeError, OSError) as exc: raise FileNotFoundError('Cannot query registry key [%s]. %s' % (key, exc))
def find_msys2_cairo(cairo): swpath = r"Software\Microsoft\Windows\CurrentVersion\Uninstall" for root in [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]: with OpenKey(root, swpath) as swkey: keys, _, _ = QueryInfoKey(swkey) for i in range(0, keys): subpath = EnumKey(swkey, i) with OpenKey(root, swpath + "\\" + subpath) as subkey: try: name, _ = QueryValueEx(subkey, 'DisplayName') loc, _ = QueryValueEx(subkey, 'InstallLocation') if name.startswith('MSYS2'): dirs = [ d for d in listdir(loc) if isdir(join(loc, d)) ] for d in dirs: libdir = join(loc, d, 'bin') if exists(join(libdir, cairo)): return libdir except: pass return False
def _get_values(hive: int, key: str, names: List[str], arch: int) -> list: try: open_reg = ConnectRegistry(None, hive) open_key = OpenKey(open_reg, key, 0, KEY_READ | arch) subkey_count, value_count, _ = QueryInfoKey(open_key) output = [] for index in range(subkey_count): values = {} subkey_name = EnumKey(open_key, index) subkey_handle = OpenKey(open_key, subkey_name) for name in names: try: values[name] = QueryValueEx(subkey_handle, name)[0] except (FileNotFoundError, TypeError): pass output.append(values) return output except (FileNotFoundError, TypeError, OSError) as exc: raise FileNotFoundError('Cannot query registry key [%s]. %s' % (key, exc))
def _delete_sub_key(root_key: int, current_key: str, arch: int) -> NoReturn: open_key = OpenKey(root_key, current_key, 0, KEY_ALL_ACCESS | arch) info_key = QueryInfoKey(open_key) for _ in range(0, info_key[0]): # NOTE:: This code is to delete the key and all sub_keys. # If you just want to walk through them, then # you should pass x to EnumKey. sub_key = EnumKey(open_key, x) # Deleting the sub_key will change the sub_key count used by EnumKey. # We must always pass 0 to EnumKey so we # always get back the new first sub_key. sub_key = EnumKey(open_key, 0) try: DeleteKey(open_key, sub_key) except OSError: _delete_sub_key(root_key, "\\".join([current_key, sub_key]), arch) # No extra delete here since each call # to delete_sub_key will try to delete itself when its empty. DeleteKey(open_key, "") open_key.Close() return
def get_pythons_from_registry(): """Search the win32 registry for installed Pythons. Returns a list of Python executables for all the Pythons installed on the host machine.""" if HAVE_WIN32_REGISTRY == 0: return [] # get the toplevel key topkey = OpenKey(HKEY_LOCAL_MACHINE,"SOFTWARE\\Python\\PythonCore") # under PythonCore will be subkeys like '2.0', '2.1', etc. nr_vers = QueryInfoKey(topkey)[0] namelist = [] # for each of those keys, get the InstallPath for i in range(nr_vers): verkey = OpenKey(topkey, "%s\\InstallPath" % EnumKey(topkey,i)) path,typ = QueryValueEx(verkey,None) name = os.path.join(path,'python.exe') if os.path.isfile(name): namelist.append(name) return namelist
def regFetch(regList): try: with open(regList, "r") as keyFile: for line in keyFile: #clean and assign variables line = line.rstrip('\n') checkRegArr = line.split(',') aReg = None aRegLoc = checkRegArr[0] aKey = checkRegArr[1] try: aRegKeyValue = checkRegArr[2] except IndexError: aRegKeyValue = 'ALL' hKeyDict = { "HKEY_CLASSES_ROOT" : HKEY_CLASSES_ROOT, "HKEY_CURRENT_USER" : HKEY_CURRENT_USER, "HKEY_LOCAL_MACHINE" : HKEY_LOCAL_MACHINE, "HKEY_USERS" : HKEY_USERS, "HKEY_CURRENT_CONFIG" : HKEY_CURRENT_CONFIG } #connect and open registry address/key aReg = ConnectRegistry(None, hKeyDict[aRegLoc.upper()]) opKey = OpenKey(aReg, aKey) if aRegKeyValue != 'ALL': try: #Will output value:data pair for specific registry key value if (QueryInfoKey(opKey)[1] == 0): #Check for empty registry key print("NO VALUES FOUND IN REGISTRY: %s\\%s\n" %(aRegLoc, aKey)) else: for i in range(1024): if EnumValue(opKey,i)[0] == aRegKeyValue: #Check to ensure current registry key is the same as user specified key aKeyValData = EnumValue(opKey,i)[1] if (aKeyValData != ""): print("The registry value of %s\\%s -> %s, is:" %(aRegLoc, aKey, aRegKeyValue)) print("--> %s : %s" %(aRegKeyValue, aKeyValData)) else: print("The registry value of %s\\%s -> %s, is:" %(aRegLoc, aKey, aRegKeyValue)) print("--> %s : No Data Assigned" %(aRegKeyValue)) except WindowsError as WinErr: if WinErr.args[3] == 259: #If the WinErr code is 259 aka No more data available, continue loop print("") continue else: print(WinErr) else: try: #Will output all values:data pairs in a registry key if (QueryInfoKey(opKey)[1] == 0): print("NO VALUES FOUND IN REGISTRY: %s\\%s\n" %(aRegLoc, aKey)) else: print("Found these in registry %s\\%s:" %(aRegLoc, aKey)) for i in range(1024): bRegKeyValue = EnumValue(opKey,i)[0] bKeyValData = EnumValue(opKey,i)[1] print("--> %s : %s" %(bRegKeyValue, bKeyValData)) except WindowsError as WinErr: if WinErr.args[3] == 259: #If the WinErr code is 259 aka No more data available, continue loop print("") continue else: print(WinErr) except IndexError as indexErr: raise SystemExit("Usage: %s -r <registry_key_file>" %(argv[0])) except FileNotFoundError as noFile: raise SystemExit("File does not exist or cannot be found: %s" %(regList)) except IsADirectoryError as dirError: raise SystemExit("Directory specified when looking for file: %s" %(regList)) except PermissionError as permError: raise SystemExit("Incorrect permissions on file %s or %s" %(regList, argv[0]))