def del_key(self, path): key = win32api.RegOpenKeyEx(self.root, path, 0, self.flags) m_item = win32api.RegEnumKeyEx(key) if not m_item: reg_parent, subkey_name = os.path.split( path) # 获得父路径名字 和自己的名字,而不是路径 try: key_parent = win32api.RegOpenKeyEx(self.root, reg_parent, 0, self.flags) # 看这个节点是否可被访问 win32api.RegDeleteKeyEx(key_parent, subkey_name) # 删除这个节点 return except Exception as e: print("Bently 被拒绝访问") return for item in win32api.RegEnumKeyEx(key): # 递归加子节点 strRecord = item[0] # 采用key的第一个节点,item里面是元组,获取第一个名字。就是要的子项名字 newpath = path + '\\' + strRecord self.del_key(newpath) # 删除父节点 root_parent, child_name = os.path.split(path) try: # 看这个节点是否可被访问 current_parent = win32api.RegOpenKeyEx(self.root, root_parent, 0, self.flags) win32api.RegDeleteKeyEx(current_parent, child_name) except Exception as e: print("Bently 被拒绝访问") return
def GetRPath(): keyName = "SOFTWARE\\R-core\\R" kHandle = None try: kHandle = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, keyName, 0, win32con.KEY_READ) rVersion, reserved, kclass, lastwrite = win32api.RegEnumKeyEx( kHandle)[-1] win32api.RegCloseKey(kHandle) kHandle = None keyName = keyName + "\\" + rVersion kHandle = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, keyName, 0, win32con.KEY_READ) except: try: kHandle = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, keyName, 0, win32con.KEY_READ) rVersion, reserved, kclass, lastwrite = win32api.RegEnumKeyEx( kHandle)[-1] win32api.RegCloseKey(kHandle) kHandle = None keyName = keyName + "\\" + rVersion kHandle = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, keyName, 0, win32con.KEY_READ) except: vim.command("let s:rinstallpath = 'Key not found'") if kHandle: (kname, rpath, vtype) = win32api.RegEnumValue(kHandle, 0) win32api.RegCloseKey(kHandle) if kname == 'InstallPath': vim.command("let s:rinstallpath = '" + rpath + "'") else: vim.command("let s:rinstallpath = 'Path not found'")
def loadDLLsInCache(directory=None): if directory: for source in os.listdir(directory): dirpath = os.path.join(directory, source) if os.path.isdir(dirpath): for e in os.listdir(dirpath): if e.lower().endswith(".dll"): # dllHandle = loadDLL(dllName) dllPath = os.path.join(dirpath, e) LOGGER.debug("Loading {} for {}".format( dllPath, source)) if source not in DLLCACHE: DLLCACHE[source] = {} try: dllHandle = loadDLL(dllPath) DLLCACHE[source][e] = dllHandle except pywintypes.error as exc: LOGGER.warn("Error loading {}: {}".format( dllPath, exc)) return keyName = u'SYSTEM\\CurrentControlSet\\Services\\EventLog' h1 = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) for (typeName, _, __, ___) in win32api.RegEnumKeyEx(h1): keyName = u'SYSTEM\\CurrentControlSet\\Services\\EventLog\\{}'.format( typeName) h2 = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) for (sourceName, _, __, ___) in win32api.RegEnumKeyEx(h2): keyName = u'SYSTEM\\CurrentControlSet\\Services\\EventLog\\{}\\{}'.format( typeName, sourceName) h3 = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, keyName, 0, win32con.KEY_READ) LOGGER.debug("Enumerating {}".format(keyName)) try: dllNames = win32api.RegQueryValueEx( h3, "EventMessageFile")[0].split(";") if sourceName not in DLLCACHE: DLLCACHE[sourceName] = {} for dllName in dllNames: if dllName: dllHandle = loadDLL(dllName) DLLCACHE[sourceName][dllName] = dllHandle except pywintypes.error as e: if e.args[0] == 2: # value not found pass else: raise e
def get_all_installed_software(): reg_root = win32con.HKEY_LOCAL_MACHINE reg_paths = [ r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", r"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall", r"Software\Microsoft\Windows\CurrentVersion\Uninstall" ] rst_list = [] for path in reg_paths: pkey = win32api.RegOpenKeyEx(reg_root, path) for item in win32api.RegEnumKeyEx(pkey): value_paths = path + "\\" + item[0] #print(value_paths) try: vkey = win32api.RegOpenKeyEx(reg_root, value_paths) DisplayName, key_type = win32api.RegQueryValueEx( vkey, "DisplayName") UninstallString, key_type = win32api.RegQueryValueEx( vkey, "UninstallString") #print({'name':DisplayName,'Uninstall string':UninstallString}) rst_list.append((DisplayName, UninstallString)) win32api.RegCloseKey(vkey) except: pass win32api.RegCloseKey(pkey) return rst_list
def get_sub_keys(self): """get key's sub keys""" key = self.get_key() for item in win32api.RegEnumKeyEx(key): yield item[0] key.close()
def reset_intellij(records): """ :return: """ import os import win32api import win32con win32api.MessageBox(None, '按任意键开始重置试用信息', '开始重置', win32con.MB_OK) key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'SOFTWARE\\JavaSoft\\Prefs\\jetbrains') if key: text = '' for (name, *_) in win32api.RegEnumKeyEx(key): if name in records: try: win32api.RegDeleteTree(key, name) text += '删除注册表: %s\n' % name evaluation_key_path, other_xml_path = records[name] os.remove(evaluation_key_path) text += '删除文件: %s\n' % evaluation_key_path os.remove(other_xml_path) text += '删除文件: %s\n' % other_xml_path except Exception as ex: win32api.MessageBox(None, ex, '异常信息', win32con.MB_OK | win32con.ICON_ERROR) win32api.RegCloseKey(key) win32api.MessageBox(None, text, '重置完成', win32con.MB_OK)
def _get_user_keys(): ''' This will return the hive 'const' value and some registry keys where installed software information has been known to exist for the HKEY_USERS hive ''' user_hive_and_keys = {} user_keys = [] users_hive = win32con.HKEY_USERS #skip some built in and default users since software information in these #keys is limited skip_users = ['.DEFAULT', 'S-1-5-18', 'S-1-5-19', 'S-1-5-20'] sw_uninst_key = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall" reg_handle = win32api.RegOpenKeyEx( users_hive, '', 0, win32con.KEY_READ) for name, num, blank, time in win32api.RegEnumKeyEx(reg_handle): #this is some identical key of a sid that contains some software names #but no detailed information about the software installed for that user if '_Classes' in name: break if name not in skip_users: usr_sw_uninst_key = "\\".join([name, sw_uninst_key]) user_keys.append(usr_sw_uninst_key) user_hive_and_keys[users_hive] = user_keys return user_hive_and_keys
def get_user_paths(): try: keyh = win32api.RegOpenKeyEx( win32con.HKEY_USERS, None, 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: return 0 paths = [] subkeys = win32api.RegEnumKeyEx(keyh) for subkey in subkeys: try: subkeyh = win32api.RegOpenKeyEx( keyh, subkey[0] + "\\Environment", 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: pass else: try: path, type = win32api.RegQueryValueEx(subkeyh, "PATH") try: user_sid = win32security.ConvertStringSidToSid(subkey[0]) except: print "WARNING: Can't convert sid %s to name. Skipping." % subkey[ 0] continue paths.append(user(user_sid), path) except: pass return paths
def 系统_取Python目录(): try: key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', 0,win32con.KEY_ALL_ACCESS) 版本 = win32api.RegQueryValueEx(key, 'Path') # 遍历注册表下目录 win32api.RegCloseKey(key) 匹配 = re.findall(r'\b[A-Z]:\\.*?python\b', 版本[0]) if 匹配: return 匹配[0] + "\\" except: pass try: p = subprocess.Popen("where python", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 结果 = p.stdout.readlines()[0].decode('utf8') if 结果.find("python") != -1: return os.path.split(结果.split("\n")[0])[0] + "\\" except: pass try: key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\\Python\\PythonCore', 0, win32con.KEY_ALL_ACCESS) 版本 = win32api.RegEnumKeyEx(key)[0][0] # 遍历注册表下目录 win32api.RegCloseKey(key) key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\\Python\\PythonCore\\{}\\InstallPath'.format(版本), 0, win32con.KEY_ALL_ACCESS) 目录 = win32api.RegQueryValueEx(key, '')[0] win32api.RegCloseKey(key) if 目录.endswith('\\'): return 目录 return 目录 + "\\" except: return ''
def _get_reg_software(): ''' This searches the uninstall keys in the registry to find a match in the sub keys, it will return a dict with the display name as the key and the version as the value ''' reg_software = {} #This is a list of default OS reg entries that don't seem to be installed #software and no version information exists on any of these items ignore_list = ['AddressBook', 'Connection Manager', 'DirectDrawEx', 'Fontcore', 'IE40', 'IE4Data', 'IE5BAKEX', 'IEData', 'MobileOptionPack', 'SchedulingAgent', 'WIC' ] encoding = locale.getpreferredencoding() #attempt to corral the wild west of the multiple ways to install #software in windows reg_entries = dict(list(_get_user_keys().items()) + list(_get_machine_keys().items())) for reg_hive, reg_keys in reg_entries.items(): for reg_key in reg_keys: try: reg_handle = win32api.RegOpenKeyEx( reg_hive, reg_key, 0, win32con.KEY_READ) except Exception: pass #Unsinstall key may not exist for all users for name, num, blank, time in win32api.RegEnumKeyEx(reg_handle): if name[0] == '{': break prd_uninst_key = "\\".join([reg_key, name]) #These reg values aren't guaranteed to exist prd_name = _get_reg_value( reg_hive, prd_uninst_key, "DisplayName") try: prd_name = prd_name.decode(encoding) except Exception: pass prd_ver = _get_reg_value( reg_hive, prd_uninst_key, "DisplayVersion") if name not in ignore_list: if prd_name != 'Not Found': reg_software[prd_name] = prd_ver return reg_software
def list_key(self, key): sub_key_list = [] if key: for sub_key in win32api.RegEnumKeyEx(key): # win32api.RegDeleteKeyEx(sub_key) sub_key_list.append(sub_key[0]) return sub_key_list else: return None
def get_subkeys(self): subkey_objects = [] try: subkeys = win32api.RegEnumKeyEx(self.get_keyh()) for subkey in subkeys: subkey_objects.append(regkey(self.get_name() + "\\" + subkey[0])) except: pass return subkey_objects
def get_mime_types(): try: hk = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, r"MIME\Database\Content Type") items = win32api.RegEnumKeyEx(hk) except win32api.error, details: logger.info("win32api error fetching mimetypes: %s", details) items = []
def _update_wsl_distros(): global ctx, registry_key_handle, wsl_distros, registry_access_flags # make sure registry is open if not registry_key_handle: _initialize_key() distro_handle = None try: # check for registry changes result = win32event.WaitForSingleObjectEx(key_event, 0, False) # for testing if False: print( f"WAIT - {result=} (looking for 'win32con.WAIT_OBJECT_0')") print(f'WAIT - {win32con.WAIT_OBJECT_0=})') print(f'WAIT - {win32con.WAIT_ABANDONED=})') print(f'WAIT - {win32con.WAIT_TIMEOUT=})') if result == win32con.WAIT_OBJECT_0: # registry has changed since we last read it, load the distros subkeys = win32api.RegEnumKeyEx(registry_key_handle) for subkey in subkeys: #print(f'{subkey=}') distro_handle = win32api.RegOpenKeyEx( registry_key_handle, subkey[0], 0, registry_access_flags) #print(f"{distro_handle=}") distro_name = win32api.RegQueryValueEx( distro_handle, 'DistributionName')[0] #print(f'{distro_name=}') wsl_distros.append(distro_name) win32api.RegCloseKey(distro_handle) # reset the event, will be set by system if reg key changes win32event.ResetEvent(key_event) elif result != win32con.WAIT_TIMEOUT: # something unexpected happened error = win32api.GetLastError() _close_key() raise Exception( 'failed while checking for wsl registry updates: {result=}: {error=}' ) except WindowsError: if distro_handle: win32api.RegCloseKey(distro_handle) log_exception(f'[_update_wsl_distros()] {sys.exc_info()[1]}')
def get_all_installed_software(): rst_dict = {} for path in reg_paths: pkey = win32api.RegOpenKeyEx(reg_root, path) for item in win32api.RegEnumKeyEx(pkey): value_paths = path + '\\' + item[0] try: vkey = win32api.RegOpenKeyEx(reg_root, value_paths) display_name, key_type = win32api.RegQueryValueEx(vkey, "DisplayName") uninstall_string, key_type = win32api.RegQueryValueEx(vkey, "UninstallString") rst_dict[display_name] = uninstall_string.replace('"', '') win32api.RegCloseKey(vkey) except: pass win32api.RegCloseKey(pkey) return rst_dict
def main(): with open("./service_bin.txt", "w") as fd: read_perm = ( win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE ) hkey = win32api.RegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE, "SYSTEM\ControlSet001\Services", 0, read_perm ) names = [ data[0] for data in win32api.RegEnumKeyEx(hkey) ] for name in names: name = name.lower() fd.write("=========== %s ============\n" % name) # print("=========== %s ============" % name) # Image Path try: subkey = win32api.RegOpenKeyEx( hkey, name, 0, read_perm ) image_path = win32api.RegQueryValueEx( subkey, "ImagePath" ) path = win32api.ExpandEnvironmentStrings( image_path[0] ) path = path.lower() except pywintypes.error: path = "" fd.write("Image Path: %s\n" % path) # print("Image Path: ", path) # Service DLL try: subkey = win32api.RegOpenKeyEx( hkey, "%s\Parameters" % name, 0, read_perm ) service_dll = win32api.RegQueryValueEx( subkey, "ServiceDll" ) path = win32api.ExpandEnvironmentStrings( service_dll[0] ) path = path.lower() except pywintypes.error as e: path = "" fd.write("Service DLL: %s\n" % path) # print("Service DLL: ", path) fd.write("\n\n")
def main(): print __doc__ print "Start cleaning registry ..." print "" for view in (VIEW64, VIEW32): hRoot = HKCR for subkey1 in [r'', r'TypeLib', r'CLSID', r'Interface', r'Record']: hKey = win32api.RegOpenKeyEx(hRoot, subkey1, 0, view) for subkey2, r, c, l in win32api.RegEnumKeyEx(hKey): if subkey2.startswith(STARTSWITH_GUID) or subkey2.startswith(STARTSWITH_PROGID): print '\\'.join((HKMAP[hRoot] + VIEWMAP[view], subkey1, subkey2)).replace('\\\\', '\\') try: win32api.RegDeleteTree(hKey, subkey2) except Exception as ex : print ' failed: %s' % ex.strerror win32api.RegCloseKey(hKey) print "\nDone"
def _reg2dict_for_key(key_hdl, deep): d = {} i = 0 while True: logging.debug("i = {}".format(i)) try: k, v, t = win32api.RegEnumValue(key_hdl, i) except pywintypes.error as ex: if ex.strerror == 'No more data is available.': break else: logging.error( "_reg2dict_for_key: Failed to get Value at index {}: Exception: {}" .format(i, ex)) raise ex else: logging.debug("Value at {} = '{}'".format(i, v)) d[k] = v i += 1 if deep: for t in win32api.RegEnumKeyEx(key_hdl): sub_key_hdl = win32api.RegOpenKeyEx(key_hdl, t[0]) d[t[0]] = _reg2dict_for_key(sub_key_hdl, deep) return d
try: win32api.RegDeleteKey(hKeyRoot, hSubKey) logger.info("\tCleaning registry key %s\%s" % (rootKeyStr, hSubKey)) return 0 except pywintypes.error, e: pass try: hKey = win32api.RegOpenKeyEx(hKeyRoot, hSubKey, 0, win32con.KEY_READ) except pywintypes.error, e: logger.debug("Could not open registry key=%s\%s: %s" % (rootKeyStr, hSubKey, e[2])) return 1 try: enumKeys = win32api.RegEnumKeyEx(hKey); except pywintypes.error, e: logger.debug("Could not enum key=%s\%s: %s" % (rootKeyStr, hSubKey, str(e[2]))) return 1 for enumKey in enumKeys: RegDeleteKeyRecurse(hKeyRoot, os.path.join(hSubKey, enumKey[0])) try: logger.info("\tCleaning registry key %s\%s" % (rootKeyStr, hSubKey)) win32api.RegDeleteKey(hKeyRoot, hSubKey) except pywintypes.error, e: logger.error("Failed to delete key='%s\%s': %s" % (rootKeyStr, hSubKey,str(e[2]))) win32api.RegCloseKey(hKey)
# print(reg_parent) # print(subkey_name) # print(os.path) # ctypes.windll.user32.SystemParametersInfoW(20, 0, 'E:\\test_lj\\img8.jpg', 0) # 设置桌面壁纸 # 根节点 reg_root = win32con.HKEY_CLASSES_ROOT # 键的路径(具体路径自行修改) reg_path_parent = "Directory\\Background\\shell\\wallpaper" reg_path_children = reg_path_parent + "\\command" # 权限和参数设置 reg_flags = win32con.WRITE_OWNER | win32con.KEY_WOW64_64KEY | win32con.KEY_ALL_ACCESS try: key = win32api.RegOpenKeyEx(reg_root, reg_path, 0, reg_flags) for item in win32api.RegEnumKeyEx(key): print(item) i = 0 while True: print(win32api.RegEnumValue(key, i)) i += 1 except Exception as e: print(e) key = None pass print(key) keyFlag = False if key is None: keyFlag = False else: keyFlag = True
def remove_key (root, key): hkey = win32api.RegOpenKey (root, key) for name, reserved, klass, last_written in win32api.RegEnumKeyEx (hkey): remove_key (hkey, name) win32api.RegDeleteKey (root, key)
if source not in DLLCACHE: DLLCACHE[source] = {} try: dllHandle = loadDLL(dllPath) DLLCACHE[source][e] = dllHandle except pywintypes.error, exc: LOGGER.warn("Error loading {}: {}".format( dllPath, e)) return from IPython import embed embed() keyName = u'SYSTEM\\CurrentControlSet\\Services\\EventLog' h1 = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) for (typeName, _, __, ___) in win32api.RegEnumKeyEx(h1): keyName = u'SYSTEM\\CurrentControlSet\\Services\\EventLog\\{}'.format( typeName) h2 = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) for (sourceName, _, __, ___) in win32api.RegEnumKeyEx(h2): keyName = u'SYSTEM\\CurrentControlSet\\Services\\EventLog\\{}\\{}'.format( typeName, sourceName) h3 = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, keyName, 0, win32con.KEY_READ) LOGGER.debug("Enumerating {}".format(keyName)) try: dllNames = win32api.RegQueryValueEx( h3, "EventMessageFile")[0].split(";") if sourceName not in DLLCACHE: DLLCACHE[sourceName] = {}
def GetDefaultVerb(szExt, szCmdLine): szVerb = '' #print 'GetDefaultVerb' #return #//File extension string equals to the registry key name. #//Value of this key points to another registry key describing shell actions #//for given file format (described by file extension string) szKey = '' if FindExecutableKey(szExt, szKey): #//TOFIX lstrcpyn szKey2 = szKey szKey2 += '\\shell' #//See if 'shell' subkey has default value defined #//(default shell action verb for this format) szVerb = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, szKey2) if (GetRegKey(HKEY_CLASSES_ROOT, szKey2, szVerb) == ERROR_SUCCESS) and len(szVerb) > 0: #//test if the verb is valid (must have valid 'command' subkey) szKey2 += '\\' szKey2 += szVerb szKey2 += '\\command' #//default value of '\\shell\\VERB\\command' subkey (replace VERB with actual value) #//gives us command line string (app + parameters) if GetRegKey(HKEY_CLASSES_ROOT, szKey2, szCmdLine) == ERROR_SUCCESS: return True szCmdLine = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, szKey2) if len(szCmdLine) > 0: return szVerb, True #//no default verb defined else: #//test for presence of standard 'open' subkey #//TOFIX lstrcpyn szKey2 = szKey #print szKey2 #szKey2 += '\\shell\\open\\command' szKey2 += '\\shell\\shell\\open\\command' # auf meinem pc francesco #print szKey2 #TODO szCmdLine = '' #szCmdLine = win32api.RegQueryValue (win32con.HKEY_CLASSES_ROOT, szKey2) if len(szCmdLine) > 0: szVerb = 'open' #TODO: it works? if GetRegKey(HKEY_CLASSES_ROOT, szKey2, szCmdLine) == ERROR_SUCCESS: szVerb = _('open') return szVerb, True #//else (last chance to find default verb) #//take first available subkey under 'shell' #//TOFIX lstrcpyn szKey2 = szKey szKey2 += '\\shell' #//enumerate subkeys until we find first subkey name #HKEY hkey; #RegOpenKeyEx(key, subKey , reserved , sam ) try: win32api.RegOpenKeyEx(win32con.HKEY_CLASSES_ROOT, szKey2, 0, KEY_ENUMERATE_SUB_KEYS) #LONG retval = RegOpenKeyEx(HKEY_CLASSES_ROOT, szKey2, 0, KEY_ENUMERATE_SUB_KEYS, &hkey); ##retval = 0, #TODO: returns tuple? retval = win32api.RegEnumKeyEx(hkey) #retval = RegEnumKeyEx(hkey, 0, szVerb, &datasize, NULL, NULL, NULL, NULL); #RegCloseKey(hkey); win32api.RegCloseKey(hkey) #if (retval == ERROR_SUCCESS): if (retval != 0): #//test if the verb is valid (must have valid 'command' subkey) szKey2 = '\\' szKey2 += szVerb szKey2 += '\\command' #//default value of '\\shell\\VERB\\command' subkey (replace VERB with actual value) #//gives us command line string (app + parameters) #TODO: it works? if GetRegKey(HKEY_CLASSES_ROOT, szKey2, szCmdLine) == ERROR_SUCCESS: return True szCmdLine = win32api.RegQueryValue( win32con.HKEY_CLASSES_ROOT, szKey2) return szVerb, True except: pass return szVerb, False