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 create_rpt_port(self, name='RPT1:'): base_path = (r'SYSTEM\ControlSet001\Control' r'\Print\Monitors\Redirected Port') port_name = name try: _ = OpenKey( HKEY_LOCAL_MACHINE, r'{base}\Ports\{port}'.format(base=base_path, port=port_name), 0, KEY_ALL_ACCESS) print "There is already a port named :{}".format(port_name) return False except WindowsError: try: reg_key = OpenKey(HKEY_LOCAL_MACHINE, base_path, 0, KEY_ALL_ACCESS) new_key = CreateKey(reg_key, 'Ports') reg_key = CreateKey(new_key, port_name) SetValueEx(reg_key, 'Description', 0, REG_SZ, 'Redirected Port') SetValueEx(reg_key, 'Command', 0, REG_SZ, '') SetValueEx(reg_key, 'Arguments', 0, REG_SZ, '') SetValueEx(reg_key, 'Printer', 0, REG_SZ, '') SetValueEx(reg_key, 'Output', 0, REG_DWORD, 0) SetValueEx(reg_key, 'Description', 0, REG_DWORD, 0) SetValueEx(reg_key, 'ShowWindow', 0, REG_DWORD, 0) SetValueEx(reg_key, 'RunUser', 0, REG_DWORD, 0) SetValueEx(reg_key, 'Delay', 0, REG_DWORD, 300) SetValueEx(reg_key, 'LogFileUse', 0, REG_DWORD, 0) SetValueEx(reg_key, 'LogFileDebug', 0, REG_DWORD, 0) SetValueEx(reg_key, 'PrintError', 0, REG_DWORD, 0) result = self.__restart_win_service('Spooler') return result except Exception: # noqa return False
def __get_binary_path(name): binary = '' if sys.platform == 'linux2': binary = Popen('which %s' % name, stdout=PIPE, shell=True).stdout.read().strip() elif sys.platform == 'win32': if name == 'soffice': key = OpenKey(HKEY_LOCAL_MACHINE, (r'SOFTWARE\OpenOffice.org' r'\Layers\OpenOffice.org\3'), 0, KEY_ALL_ACCESS) sub_key = QueryValueEx(key, "OFFICEINSTALLLOCATION")[0] binary = os.path.join(sub_key, 'program', 'soffice.exe') elif name == 'firefox' or name == 'thunderbird': key = OpenKey(HKEY_LOCAL_MACHINE, r'Software\Mozilla\Mozilla ' + name.capitalize(), 0, KEY_ALL_ACCESS) sub_key = QueryValueEx(key, "CurrentVersion")[0] key = OpenKey( HKEY_LOCAL_MACHINE, r'Software\Mozilla\Mozilla ' + name.capitalize() + '\\' + sub_key + '\\Main', 0, KEY_ALL_ACCESS) binary = QueryValueEx(key, "PathToExe")[0] if binary: return binary else: print "Binary not found." return False
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 get_installed_products(): """ Enumerate all installed products. """ products = {} hkey_products = OpenKey(HKEY_LOCAL_MACHINE, PRODUCTS_KEY, 0, KEY_ALL_ACCESS) try: product_index = 0 while True: product_guid = EnumKey(hkey_products, product_index) hkey_product_properties = OpenKey( hkey_products, product_guid + r'\InstallProperties', 0, KEY_ALL_ACCESS) try: value = QueryValueEx(hkey_product_properties, 'DisplayName')[0] except WindowsError, exception: if exception.winerror != 2: raise value = '<unknown>' CloseKey(hkey_product_properties) products[product_guid] = value product_index += 1 except WindowsError, exceptione: if exceptione.winerror != 259: print exceptione.strerror + '.', 'error', exceptione.winerror
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 find_exe_in_registry(keys): if not keys: return "" try: from _winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER except ImportError: from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER import shlex command = "" for path in keys: try: key = OpenKey(HKEY_LOCAL_MACHINE, path) command = QueryValue(key, "") break except OSError: try: key = OpenKey(HKEY_CURRENT_USER, path) command = QueryValue(key, "") break except OSError: pass else: return "" if not command: return "" return shlex.split(command)[0]
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 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 _find_exe_in_registry(self): try: from _winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER except ImportError: from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER import shlex keys = (r"SOFTWARE\Classes\FirefoxHTML\shell\open\command", r"SOFTWARE\Classes\Applications\firefox.exe\shell\open\command") command = "" for path in keys: try: key = OpenKey(HKEY_LOCAL_MACHINE, path) command = QueryValue(key, "") break except OSError: try: key = OpenKey(HKEY_CURRENT_USER, path) command = QueryValue(key, "") break except OSError: pass else: return "" if not command: return "" return shlex.split(command)[0]
def _Find(Key, SubKey): #print 'Key/SubKey',Key,SubKey key = OpenKey(Key, SubKey) N, v, w = QueryInfoKey(key) for i in range(N): DB_Name = EnumKey(key, i) #print 'DB_Name',key,i,DB_Name DB_Key = SubKey + '\\' + DB_Name #print 'Key/DB_Key',Key,DB_Key try: key_sub = OpenKey(Key, DB_Key) M, v, w = QueryInfoKey(key_sub) for ii in range(v): key_value = EnumValue(key_sub, ii) # NOT YET COMPLETE if key_value[0] in ['DBQ', 'Database', 'EngineName']: ODBC_DBs.append([DB_Name, key_value[1]]) CloseKey(key_sub) except: if Key == HKEY_CURRENT_USER: print 'ODBC Database not found: HKEY_CURRENT_USER', DB_Key else: print 'ODBC Database not found: HKEY_LOCAL_MACHINE', DB_Key CloseKey(key)
def findgrcompiler(): global grcompiler if sys.platform == 'win32': if getattr(sys, 'frozen', None): grcompiler = os.path.join(sys._MEIPASS, 'grcompiler.exe') return grcompiler try: from _winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE node = "Microsoft\\Windows\\CurrentVersion\\Uninstall\\Graphite Compiler_is1" if sys.maxsize > 1 << 32: r = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Wow6432Node\\" + node) else: r = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\" + node) p = QueryValue(r, "InstallLocation") grcompiler = os.path.join(p, "GrCompiler.exe") except WindowsError: for p in os.environ['PATH'].split(';'): a = os.path.join(p, 'grcompiler.exe') if os.path.exists(a): grcompiler = a break elif sys.platform == 'darwin' and getattr(sys, 'frozen', None): grcompiler = os.path.join(sys._MEIPASS, 'grcompiler') return grcompiler else: for p in os.environ['PATH'].split(':'): a = os.path.join(p, "grcompiler") if os.path.exists(a): grcompiler = a break return grcompiler
def get_winroot_from_registry(): """Get the Windows directory, e.g. c:\WINDOWS, from the registry, or None if not found or error.""" if HAVE_WIN32_REGISTRY == 0: return None try: # SystemRoot is found here on win9x machines topkey = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion") path, typ = QueryValueEx(topkey, 'SystemRoot') return path except: pass try: # On NT/2k/etc., SystemRoot is under 'Windows NT' instead topkey = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion") path, typ = QueryValueEx(topkey, 'SystemRoot') return path except: pass # maybe it doesn't exist under some versions of win32 return None
def search_name(locals, prog_path): """use the prog_path to find out the program display name locals: -- (main_key, sub_key) prog_path: -- program execute path return prog_name """ for local in locals: key = OpenKey(*local) key_no = QueryInfoKey(key)[0] for index in xrange(key_no): key_name = EnumKey(key, index) app_key = OpenKey(key, key_name) for value_name in ('InstallLocation', 'LocationRoot', 'UninstallString'): try: value_data = QueryValueEx(app_key, value_name)[0] if value_data and (value_data.startswith(prog_path) or prog_path.startswith(value_data)): prog_name = QueryValueEx(app_key, 'DisplayName')[0] return prog_name except WindowsError: pass return None
def main(): """ Enumerate all installed products, go through all components and check if client refences point to valid products. Remove references to non-existing products if the user allowed it. """ hkey_components = OpenKey(HKEY_LOCAL_MACHINE, COMPONENTS_KEY, 0, KEY_ALL_ACCESS) missing_products = get_missing_products(hkey_components) print('Missing products refer the following components:') for product_guid in sorted(missing_products.keys()): if product_guid[1:] == '0' * 31: continue print('Product', transpose_guid(product_guid) + ':') for component_guid, component_file in missing_products[product_guid]: print(' ' + transpose_guid(component_guid), '=', component_file) print('Remove all references to product', transpose_guid(product_guid) + '? [y/n]') if strtobool(raw_input().lower()): for component_guid, component_file in missing_products[ product_guid]: hkey_component = OpenKey(hkey_components, component_guid, 0, KEY_ALL_ACCESS) print( 'Removing reference in ' + transpose_guid(component_guid), '=', component_file) DeleteValue(hkey_component, product_guid) CloseKey(hkey_component) else: print('Cancelled removal of product', transpose_guid(product_guid)) CloseKey(hkey_components)
def set_user_env(reg, parent=None): """Set HKCU (current user) environment variables""" reg = listdict2envdict(reg) types = dict() key = OpenKey(HKEY_CURRENT_USER, "Environment") for name in reg: try: _x, types[name] = QueryValueEx(key, name) except WindowsError: types[name] = REG_EXPAND_SZ key = OpenKey(HKEY_CURRENT_USER, "Environment", 0, KEY_SET_VALUE) for name in reg: SetValueEx(key, name, 0, types[name], reg[name]) try: from win32gui import SendMessageTimeout from win32con import (HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG) SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 5000) except ImportError: QMessageBox.warning( parent, _("Warning"), _("Module <b>pywin32 was not found</b>.<br>" "Please restart this Windows <i>session</i> " "(not the computer) for changes to take effect."))
def get_installed_products(): """ Enumerate all installed products. """ products = {} hkey_products = OpenKey(HKEY_LOCAL_MACHINE, PRODUCTS_KEY, 0, KEY_ALL_ACCESS) try: product_index = 0 while True: product_guid = EnumKey(hkey_products, product_index) hkey_product_properties = OpenKey( hkey_products, product_guid + r'\InstallProperties', 0, KEY_ALL_ACCESS) try: value = QueryValueEx(hkey_product_properties, 'DisplayName')[0] except WindowsError as oXcpt: if oXcpt.winerror != 2: raise value = '<unknown>' CloseKey(hkey_product_properties) products[product_guid] = value product_index += 1 except WindowsError as oXcpt: if oXcpt.winerror != 259: print(oXcpt.strerror + '.', 'error', oXcpt.winerror) CloseKey(hkey_products) print('Installed products:') for product_key in sorted(products.keys()): print(transpose_guid(product_key), '=', products[product_key]) print() return products
def get_prog_command(progid): """use the program id to find out program path params: progid - program id in registry """ open_command = None edit_command = None sub_key = '\\'.join([progid, 'shell', 'edit', 'command']) try: key = OpenKey(HKEY_CLASSES_ROOT, sub_key) edit_command = QueryValueEx(key, None)[0] except WindowsError: pass sub_key = '\\'.join([progid, 'shell', 'open', 'command']) try: key = OpenKey(HKEY_CLASSES_ROOT, sub_key) open_command = QueryValueEx(key, None)[0] except WindowsError: pass if not (open_command or edit_command): return None return edit_command or open_command
def activate(self, event): self.Unbind(wx.EVT_IDLE) if platform=='win32': from _winreg import OpenKey, QueryValueEx, HKEY_CURRENT_USER, REG_SZ, REG_EXPAND_SZ progs=getenv("PROGRAMFILES", '\\').decode('mbcs') for i in listdir(progs): if i.lower().startswith("x-plane") and isdir(join(progs, i, "Custom Scenery")): folder=join(progs, i) break else: folder=getenv("USERPROFILE", '\\').decode('mbcs') # fallback try: handle=OpenKey(HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders') (v,t)=QueryValueEx(handle, 'Desktop') handle.Close() if t==REG_EXPAND_SZ: dirs=v.rstrip('\0').decode('mbcs').strip().split('\\') for i in range(len(dirs)): if dirs[i][0]==dirs[i][-1]=='%': dirs[i]=getenv(dirs[i][1:-1],dirs[i]).decode('mbcs') v='\\'.join(dirs) if t in [REG_SZ,REG_EXPAND_SZ] and isdir(v): folder=desktop=v for i in listdir(desktop): if i.lower().startswith("x-plane") and isdir(join(desktop, i, "Custom Scenery")): folder=join(desktop, i) break except: pass else: try: home=expanduser('~').decode(getfilesystemencoding() or 'utf-8') # Unicode so paths listed as unicode desktop=join(home, "Desktop") except: home=desktop=u'/' for i in listdir(desktop): if i.lower().startswith("x-plane") and isdir(join(desktop, i, "Custom Scenery")): folder=join(desktop, i) break else: for i in listdir(home): if i.lower().startswith("x-plane") and isdir(join(home, i, "Custom Scenery")): folder=join(home, i) break else: folder=home if not self.folder: style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER if 'DD_DIR_MUST_EXIST' in dir(wx): style|=wx.DD_DIR_MUST_EXIST if not platform.startswith('linux'): dlg=wx.DirDialog(self.dummy, 'Choose the folder that contains the aircraft or scenery that you want to publish', folder, style) else: # displayed in title on linux dlg=wx.DirDialog(self.dummy, 'Select aircraft or scenery folder', folder, style) if dlg.ShowModal()!=wx.ID_OK: exit(1) self.folder = dlg.GetPath() publish(unicodeify(self.folder), self) exit(0)
def test_with(self): from _winreg import OpenKey with OpenKey(self.root_key, self.test_key_name) as key: with OpenKey(key, "sub_key") as sub_key: assert key.handle != 0 assert sub_key.handle != 0 assert key.handle == 0 assert sub_key.handle == 0
def test_delete(self): from _winreg import OpenKey, KEY_ALL_ACCESS, DeleteValue, DeleteKey key = OpenKey(self.root_key, self.test_key_name, 0, KEY_ALL_ACCESS) sub_key = OpenKey(key, "sub_key", 0, KEY_ALL_ACCESS) for name, value, type in self.test_data: DeleteValue(sub_key, name) DeleteKey(key, "sub_key")
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 get_open_with_progs(ext): """get the open with progids @params ext -- file extention @return name progrid command """ import re # find all keys key = OpenKey(HKEY_CLASSES_ROOT, None) key_no = QueryInfoKey(key)[0] all_keys = [] for index in xrange(key_no): all_keys.append(EnumKey(key, index)) # try to find open with progids sub_key = '\\'.join([ext, 'OpenWithProgids']) try: key = OpenKey(HKEY_CLASSES_ROOT, sub_key) except WindowsError: return None # add default program progids = [] logger.debug('current ext: %s', ext) logger.debug('all key number: %s', len(all_keys)) # enum value under the key value_no = QueryInfoKey(key)[1] for index in xrange(value_no): value = EnumValue(key, index)[0] value and logger.debug('find progid: %s', value) if value and value in all_keys: progids.append(value) logger.debug('open with progrids: %s', progids) # get the information about the progids exes = [] for progid in progids: name = get_prog_name(progid) command = get_prog_command(progid) if name and command: exes.append((name, progid, command)) if command and not name: match = re.search(u'.+\\\\(\w+)\.exe', command, flags=re.IGNORECASE) if match: name = match.group(1) exes.append((name, progid, command)) return exes
def get_install_key(program): keystr = "Software\%s" % program try: key = OpenKey(HKEY_LOCAL_MACHINE,keystr) except WindowsError: try: key = OpenKey(HKEY_CURRENT_USER,keystr) except WindowsError: raise WindowsError, "%s is not installed on this computer" % program return key
def __win32_finddll(): try: import winreg except ImportError: # assume Python 2 from _winreg import ( OpenKey, CloseKey, EnumKey, QueryValueEx, QueryInfoKey, HKEY_LOCAL_MACHINE, ) else: 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", "GNU Ghostscript", "GPL 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 ssh_putty_hosts(): results = {} try: h = OpenKey(HKEY_USERS, '') except WindowsError: return idx = 0 try: while True: user = EnumKey(h, idx) username, domain, _ = LookupAccountSidW(user) if username is None: username = user if domain: user = domain + '\\' + user for reg_path in REG_PATHS: try: sessions = user + reg_path h2 = OpenKey(HKEY_USERS, sessions) except WindowsError: continue try: idx2 = 0 while True: session = EnumKey(h2, idx2) record = extract_info(sessions + '\\' + session) if record: if username not in results: results[username] = {} results[username].update(record) idx2 += 1 except WindowsError: pass finally: CloseKey(h2) idx += 1 except WindowsError: return results finally: CloseKey(h)
def test_readValues(self): from _winreg import OpenKey, EnumValue, QueryValueEx, EnumKey key = OpenKey(self.root_key, self.test_key_name) sub_key = OpenKey(key, "sub_key") index = 0 while 1: try: data = EnumValue(sub_key, index) except EnvironmentError, e: break assert data in self.test_data index = index + 1
def associate(ext, target, change_allusers): changed = False what = "the %s association for %s" % (change_allusers and "system" or "user", ext) goal = "associate the filetype %s with %s for %s" % (ext, target, change_allusers and "all users" or "the current user") try: if change_allusers: target_key = OpenKey(HKEY_LOCAL_MACHINE, "%s\\%s" % (SYSTEM_CLASSES, target), 0, KEY_QUERY_VALUE) else: target_key = OpenKey(HKEY_CLASSES_ROOT, target, 0, KEY_QUERY_VALUE) except WindowsError, e: raise DistutilsSetupError("I was going to %s, but that won't work because the %s class does not exist in the registry, " "as far as I can tell.\n%r" % (goal, target, e))
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 appids(self): "generator, yield a 2-tuple of appid as int, installed bool pairs" with OpenKey(HKEY_CURRENT_USER, appids_key, 0, READ_AND_ENUM) as key: for name in enum_keys(key): with OpenKey(key, name) as subkey: try: installed, type = QueryValueEx(subkey, installed_name) except WindowsError as e: if e.winerror != 2: raise #error 2 is "Not Found" continue installed = 0 yield int(name), bool(installed)