def get_registry_key_value(root_folder: str, key_path: str, sub_key: str): if "hkey_local_machine" in root_folder.lower(): root_folder = ConnectRegistry(None, HKEY_LOCAL_MACHINE) elif "hkey_classes_root" in root_folder.lower(): root_folder = ConnectRegistry(None, HKEY_CLASSES_ROOT) elif "hkey_current_config" in root_folder.lower(): root_folder = ConnectRegistry(None, HKEY_CURRENT_CONFIG) elif "hkey_current_user" in root_folder.lower(): root_folder = ConnectRegistry(None, HKEY_CURRENT_USER) elif "hkey_users" in root_folder.lower(): root_folder = ConnectRegistry(None, HKEY_USERS) try: registry_key = OpenKey(root_folder, key_path) system_value, reg_word = QueryValueEx(registry_key, sub_key) CloseKey(registry_key) except: # key not found system_value = None return system_value
def search_reg(scope): if scope == "HKCU": a_reg = ConnectRegistry(None, HKEY_CURRENT_USER) a_key = "Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache\\" elif scope == "HKLM": a_reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) a_key = "SOFTWARE\\WOW6432Node\\NCWest\\BnS\\" else: return count = 0 try: key = OpenKey(a_reg, a_key) while True: name, value, value_type = EnumValue(key, count) if scope == "HKCU": if value == "Blade & Soul by bloodlust(x86)": game_path = name.split(".")[0].split("\\") game_path.pop() game_path.pop() # "Game path found in HKCU!" return "/".join(game_path) + "/" elif scope == "HKLM": if name == "BaseDir": # "Game path found in HKLM!" return value count += 1 except (WindowsError, OSError, FileNotFoundError): pass
def getBethesdaGameFolder(gameName): gameFolder = 'Not Detected' gameReg = Info.game_reg(gameName) try: gameFolder = QueryValueEx(OpenKey(ConnectRegistry(None, HKEY_LOCAL_MACHINE), f'SOFTWARE\\Bethesda Softworks\\{gameReg}'),"installed path")[0] except: sm('Did not find game folder in the registry (no WOW6432Node location).', exception=1) if gameFolder == 'Not Detected': try: gameFolder = QueryValueEx(OpenKey(ConnectRegistry(None, HKEY_LOCAL_MACHINE), f'SOFTWARE\\WOW6432Node\\Bethesda Softworks\\{gameReg}'),"installed path")[0] except: sm('Did not find game folder in the registry.', exception=1) return gameFolder
def steamDir() -> str: """ a function that retrieves the steam installation folder by reading the win registry :return: path to steam folder :raises KeyError: """ if 'steamDir' not in currentConfigData: save(None, 'steamDir' ) # create the config without value in case it doesn't exist if load('steamDir') is not None: return load('steamDir') # return the folder elif utilities.platform == 'win32': # get the steam directory from the windows registry # HKEY_CURRENT_USER\Software\Valve\Steam try: logger.debug('Opening windows registry...') with ConnectRegistry(None, HKEY_CURRENT_USER) as reg: aKey = OpenKey( reg, r'Software\Valve\Steam' ) # open the steam folder in the windows registry except Exception as e: logger.critical("Can't open windows registry! this is *VERY* bad!", exc_info=True) raise try: keyValue = QueryValueEx(aKey, 'SteamPath') # find the steam path save( keyValue[0], 'steamDir') # save the path, so we don't have to redo all this return keyValue[0] except: raise KeyError("Can't open/find the steam registry keys")
def registration(): import os print(sys.executable) if os.path.basename(sys.executable) == "__main__.exe": try: from winreg import ConnectRegistry, HKEY_CLASSES_ROOT, \ CreateKeyEx, SetValueEx, REG_SZ, KEY_ALL_ACCESS, KEY_SET_VALUE root = ConnectRegistry(None, HKEY_CLASSES_ROOT) policy_key = CreateKeyEx(root, r"rhythmcollective", 0, KEY_SET_VALUE) SetValueEx(policy_key, None, 0, REG_SZ, "URL:rhythmcollective") SetValueEx(policy_key, "URL Protocol", 0, REG_SZ, "") policy_key = CreateKeyEx(root, r"rhythmcollective\DefaultIcon", 0, KEY_SET_VALUE) SetValueEx(policy_key, None, 0, REG_SZ, "\"Arena.exe,1\"") policy_key = CreateKeyEx(root, r"rhythmcollective\shell\open\command", 0, KEY_ALL_ACCESS) SetValueEx(policy_key, None, 0, REG_SZ, f"\"{sys.executable}\" --from-url \"%1\"") print("registered") except OSError as an_error: print(f"unable to open registry {an_error}")
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 reg_scanner(**kwargs): try: if kwargs.get('source') == 'putty': parent_key = r"SOFTWARE\SimonTatham\PuTTY\Sessions" elif kwargs.get('source') == 'kitty': parent_key = r"SOFTWARE\9bis.com\KiTTY\Sessions" except Exception as error: print( f'Invalid source, please check configuration file or typo... -> {error}' ) parent_reg = ConnectRegistry(None, HKEY_CURRENT_USER) parent_key = OpenKey(parent_reg, parent_key) for sessions in range(int(kwargs.get('sessions'))): try: subkey_name = EnumKey(parent_key, sessions) subkey = OpenKey(parent_key, subkey_name) host = QueryValueEx(subkey, "HostName") port = QueryValueEx(subkey, "PortNumber") username = QueryValueEx(subkey, "UserName") yield (subkey_name, host[0], port[0], username[0]) except OSError as error: #print(error) break
def get_installaton_path_on_windows(fc_name): # tested for FreeCAD 0.18 import itertools from winreg import ( ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKeyEx, QueryValueEx, CloseKey, KEY_READ, EnumKey, WindowsError, ) try: root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) reg_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" akey = OpenKeyEx(root, reg_path, 0, KEY_READ) for i in itertools.count(): try: subname = EnumKey(akey, i) except WindowsError: break if subname.lower().find(fc_name.lower()) > 0: subkey = OpenKeyEx(akey, subname, 0, KEY_READ) pathname, regtype = QueryValueEx(subkey, "InstallLocation") CloseKey(subkey) return os.path.expandvars(pathname) # close key and root CloseKey(akey) CloseKey(root) return None except OSError: return None
def create_backdoor_key(path_to_startup_registry_key:str): with ConnectRegistry(None, HKEY_CURRENT_USER) as hkcu: with \ OpenKey(hkcu, path_to_startup_registry_key, 0, KEY_ALL_ACCESS) \ as startup_key: SetValueEx(startup_key, "SecurityNow", 0, REG_EXPAND_SZ, "%TEMP%\\securitynow.exe") flush_registry_changes()
def verify_registry(): regHandle = ConnectRegistry(None, HKEY_LOCAL_MACHINE) keyHandle = OpenKey(regHandle, r"SOFTWARE\Mozilla\NativeMessagingHosts\org.cryptable.pki.keymgmnt", access=KEY_READ) data = QueryValue(keyHandle, None) print(data) if data != r"C:\Program Files\Cryptable\Key Management Web Extension\org.cryptable.pki.keymgmnt.json": raise "registry verification error"
def PyCharm_go_to(file, line): """ Opens an PyCharm if not opened and moves cursor to specified file and line """ if platform.system() == 'Windows': from winreg import ConnectRegistry, OpenKey, EnumValue, HKEY_CLASSES_ROOT import subprocess reg = ConnectRegistry(None, HKEY_CLASSES_ROOT) raw_key = OpenKey(reg, r"Applications\pycharm.exe\shell\open\command") pycharm_path = "" try: i = 0 while 1: name, pycharm_path, type = EnumValue(raw_key, i) if pycharm_path: break i += 1 except WindowsError: pass pycharm_path = pycharm_path.replace('"%1"', "").strip().strip('"') project_path = Globals.workspace pycharm_process = find_process_by_name("pycharm") if pycharm_process is not None: focus_window_by_pid(pycharm_process.pid) subprocess.Popen([pycharm_path, project_path, "--line", str(line), file])
def handle_windows_reg_key(): """ Attempts to add this app to the list of apps that launch at startup checks for value in registry, creates one if it doesn't exist will update key with new location of .exe if it was moved """ from winreg import OpenKey, CloseKey, QueryValueEx, SetValueEx, ConnectRegistry, \ HKEY_CURRENT_USER, REG_SZ, KEY_ALL_ACCESS name = 'wallspotify' path = sys.executable registry = ConnectRegistry(None, HKEY_CURRENT_USER) key = OpenKey(registry, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 0, KEY_ALL_ACCESS) def add(): SetValueEx(key, name, 0, REG_SZ, path) try: data = QueryValueEx(key, name) if data[0] != path: add() except WindowsError: add() CloseKey(key)
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 check_R_dependency(): updated = False r_installfold = read_setting('Processing/Configuration/R_FOLDER') if platform.system() == 'Windows': try: aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) aKey = OpenKey(aReg, r"SOFTWARE\R-core\R") aVal = os.path.normpath(QueryValueEx(aKey, "InstallPath")[0]) if os.path.exists(aVal): if r_installfold is not None and r_installfold != aVal: r_installfold = aVal write_setting('Processing/Configuration/R_FOLDER', aVal) LOGGER.info( 'Setting ... R Install folder: {}'.format(aVal)) r_installed = True except EnvironmentError: r_installed = False write_setting('Processing/Configuration/R_FOLDER', '') write_setting('Processing/Configuration/ACTIVATE_R', False) return 'R is not installed or not configured for QGIS.\n See "Configuring QGIS to use R" in help documentation' else: # Linux/OSX - https://stackoverflow.com/a/25330049 try: subprocess.check_call(['which', 'R']) except subprocess.CalledProcessError: r_installed = False else: r_installed = True if not r_installed: write_setting('Processing/Configuration/R_FOLDER', '') write_setting('Processing/Configuration/ACTIVATE_R', False) return 'R is not installed or not configured for QGIS.\n See "Configuring QGIS to use R" in help documentation' # Get the users R script folder - returns none if not set. r_scripts_fold = read_setting('Processing/Configuration/R_SCRIPTS_FOLDER') if r_scripts_fold is None: return 'R is not installed or not configured for QGIS.\n See "Configuring QGIS to use R" in help documentation' files = glob.glob(os.path.join(PLUGIN_DIR, "R-Scripts", "Whole*.rsx")) for src_file in files: dest_file = os.path.join(r_scripts_fold, os.path.basename(src_file)) # update flag will only update if file doesnt exist or is newer and returns a tuple of # all files with a 1 if the file was copied if file_util.copy_file(src_file, dest_file, update=True)[-1]: LOGGER.info('Installing or Updating Whole-of-block analysis tool.') # # only copy if it doesn't exist or it is newer by 1 second. # if not os.path.exists(dest_file) or os.stat(src_file).st_mtime - os.stat( # dest_file).st_mtime > 1: # shutil.copy2(src_file, dest_file) return True
def get_FS2000_install_directory(): try: reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) key = OpenKey(reg, 'SOFTWARE\Wow6432Node\FS2000\Setup') install_directory = EnumValue(key, 0)[1] return install_directory except: raise RuntimeError('FS2000 must be installed')
def get_processor_name(): from winreg import ConnectRegistry, OpenKey, QueryValueEx, HKEY_LOCAL_MACHINE registry_connection = ConnectRegistry(None, HKEY_LOCAL_MACHINE) registry_key = OpenKey( registry_connection, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") name = QueryValueEx(registry_key, 'ProcessorNameString')[0] return name
def enumerate_registry_hive(top_registry_key, subkey=None): with ConnectRegistry(None, top_registry_key) as key: for subkey in get_subkeys(key): opened_key = OpenKey(top_registry_key, subkey, 0, KEY_ALL_ACCESS) get_key_values(opened_key) if subkey not None: subkey = f"{}"
def _get_clock_ghz_windows() -> float: from winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE) key = OpenKey(registry, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0") mhz, _ = QueryValueEx(key, "~MHz") ghz = mhz_to_ghz(check_cast(float, mhz)) assert 0 < ghz < 10 return ghz
def __find_store(self): try: root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) base_key = OpenKeyEx(root, EGS.LAUNCHER_PATH) data_path = QueryValueEx(base_key, "AppDataPath") self.__valid = True return data_path[0] except Exception as e: self.__context.warn( "Failed to find path, maybe it isn't installed", e)
def disablebUpdater(): try: root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) bUpdater_key = OpenKeyEx( root, r"SOFTWARE\Policies\Adobe\Adobe Acrobat\DC\FeatureLockDown") SetValueEx(bUpdater_key, "bUpdater", 0, REG_DWORD, 0) except OSError: bUpdater_key = CreateKey( root, r"SOFTWARE\Policies\Adobe\Adobe Acrobat\DC\FeatureLockDown") SetValueEx(bUpdater_key, "bUpdater", 0, REG_DWORD, 0)
def sys_bgcolor(pyplot): """Reads system preference and sets plt background accordingly""" from winreg import ConnectRegistry, HKEY_CURRENT_USER, OpenKeyEx, QueryValueEx root = ConnectRegistry(None, HKEY_CURRENT_USER) policy_key = OpenKeyEx( root, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize") light, _ = QueryValueEx(policy_key, "AppsUseLightTheme") if light: pyplot.style.use('default') else: pyplot.style.use('dark_background')
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 __get_install_path(self): try: root = ConnectRegistry(None, HKEY_CURRENT_USER) steam_key = OpenKeyEx(root, Steam.PATH) res_exe = QueryValueEx(steam_key, "SteamExe") res_path = QueryValueEx(steam_key, "SteamPath") self.__valid = True return res_exe[0], os.path.normpath(res_path[0]) except Exception as e: self.__context.warn("Failed to find path, maybe isn't installed", e)
def __get_exe_path(self): try: root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) base_key = OpenKeyEx(root, EGS.ICON_PATH) data_path = QueryValueEx(base_key, "") self.__context.dbg("data path", data_path) self.__valid = True return data_path[0].split(",")[0] except Exception as e: self.__context.warn( "Failed to find executable, maybe it isn't installed", e)
def _get_value(hive: int, key: str, value: Optional[str], arch: int) -> str: try: open_reg = ConnectRegistry(None, hive) open_key = OpenKey(open_reg, key, 0, KEY_READ | arch) value, key_type = QueryValueEx(open_key, value) # Return the first match return value except (FileNotFoundError, TypeError, OSError) as exc: raise FileNotFoundError( 'Registry key [%s] with value [%s] not found. %s' % (key, value, exc))
def get_registry_key_value(HKEYS, key, value): HANDLES = { "CLASSES_ROOT": winreg.HKEY_CLASSES_ROOT, "CURRENT_USER": winreg.HKEY_CURRENT_USER, "LOCAL_MACHINE": winreg.HKEY_LOCAL_MACHINE, "USERS": winreg.HKEY_USERS, "PERFORMANCE_DATA": winreg.HKEY_PERFORMANCE_DATA, "CURRENT_CONFIG": winreg.HKEY_CURRENT_CONFIG } key = key.replace('/', '\\') return QueryValueEx(OpenKey(ConnectRegistry(None, HANDLES[HKEYS]), key), value)
def _get_clock_ghz_windows() -> float: # Import lazily as this is only available on Windows # pylint:disable=import-outside-toplevel from winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE) key = OpenKey(registry, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0") mhz, _ = QueryValueEx(key, "~MHz") ghz = mhz_to_ghz(check_cast(float, mhz)) assert 0 < ghz < 10 return ghz
def _get_ise_path(cls): if os.name != 'nt': return None from winreg import ConnectRegistry, OpenKey, EnumValue, HKEY_CLASSES_ROOT from shlex import split reg = ConnectRegistry(None, HKEY_CLASSES_ROOT) try: key = OpenKey(reg, r'isefile\shell\open\Command') except FileNotFoundError: return None cmd = EnumValue(key, 0)[1] return os.path.dirname(split(cmd)[0])
def toggle_color_mode(): """Toggles system color scheme preference.""" from winreg import ConnectRegistry, HKEY_CURRENT_USER, REG_SZ, KEY_ALL_ACCESS, OpenKeyEx, QueryValueEx, SetValueEx, CloseKey root = ConnectRegistry(None, HKEY_CURRENT_USER) policy_key = OpenKeyEx( root, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize", access=KEY_ALL_ACCESS) light, _ = QueryValueEx(policy_key, "AppsUseLightTheme") SetValueEx(policy_key, "AppsUseLightTheme", 0, REG_SZ, str(1 - int(light))) SetValueEx(policy_key, "SystemUsesLightTheme", 0, REG_SZ, str(1 - int(light))) CloseKey(policy_key)
def windows_group_policy_path(): from winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKeyEx, QueryValueEx, REG_EXPAND_SZ, REG_SZ try: root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) policy_key = OpenKeyEx(root, r"SOFTWARE\Policies\Google\Chrome") user_data_dir, type_ = QueryValueEx(policy_key, "UserDataDir") if type_ == REG_EXPAND_SZ: user_data_dir = os.path.expandvars(user_data_dir) elif type_ != REG_SZ: return None except OSError: return None return os.path.join(user_data_dir, "Default", "Cookies")