def del_registry(self) -> None: """ Remove program from Windows registry (delete from floder context menu) """ import winreg root_registry = winreg.ConnectRegistry(None, winreg.HKEY_CLASSES_ROOT) contex_menu_key = winreg.OpenKey(root_registry, r'Directory\shell\\') try: fotosort_key = winreg.OpenKey(contex_menu_key, r'Open with FotoSort\\') except OSError: self.label_log.setText('Nothing to delete!') self.label_log.setStyleSheet('color: red') else: index = 0 while True: try: subkey = winreg.EnumKey(fotosort_key, index) winreg.DeleteKey(fotosort_key, subkey) index += 1 except OSError: break try: winreg.DeleteKey(contex_menu_key, r'Open with FotoSort') except OSError: self.label_log.setText( 'Error while deleting FotoSort from Windows registry!') self.label_log.setStyleSheet('color: red') else: self.label_log.setText( 'FotoSort successfully deleted from Windows registry!') self.label_log.setStyleSheet('color: blue')
def _remove_jupyter_here(all_users): if all_users: h_key_base = winreg.HKEY_LOCAL_MACHINE install_type = "all users" else: h_key_base = winreg.HKEY_CURRENT_USER install_type = "single user" for terminal in ('qtconsole', 'notebook', 'lab'): try: winreg.DeleteKey( h_key_base, r'Software\Classes\Directory\shell\jupyter_%s_here%s\Command' % (terminal, CONDA_ENV_LABEL.replace(" ", "_"))) winreg.DeleteKey( h_key_base, r'Software\Classes\Directory\shell\jupyter_%s_here%s' % (terminal, CONDA_ENV_LABEL.replace(" ", "_"))) winreg.DeleteKey( h_key_base, r'Software\Classes\Directory\Background\shell\jupyter_%s_here%s\Command' % (terminal, CONDA_ENV_LABEL.replace(" ", "_"))) winreg.DeleteKey( h_key_base, r'Software\Classes\Directory\Background\shell\jupyter_%s_here%s' % (terminal, CONDA_ENV_LABEL.replace(" ", "_"))) print("Jupyter %s here%s context menu entry removed for %s." % (terminal, CONDA_ENV_LABEL, install_type)) except FileNotFoundError: # If this fails it is because it was not installed, so nothing to # worry about. pass
def findWritableClassesSection(self): # first try in HKEY_CLASSES_ROOT try: writer = winreg.ConnectRegistry(None, winreg.HKEY_CLASSES_ROOT) GatoFileTestHandle = winreg.CreateKey(writer, "Gato.File.Test") winreg.DeleteKey(writer, "Gato.File.Test") return writer except WindowsError: # print "could not access HKEY_CLASSES_ROOT/Gato.File" # self.traceback.print_exc() pass # next try... try: writer = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) SoftwareSection = winreg.OpenKey(writer, "Software") ClassesSection = winreg.OpenKey(SoftwareSection, "Classes", 0, winreg.KEY_SET_VALUE) GatoFileTestHandle = winreg.CreateKey(ClassesSection, "Gato.File.Test") winreg.DeleteKey(ClassesSection, "Gato.File.Test") return ClassesSection except WindowsError: # print "could not access HKEY_CURRENT_USER/Software/Classes Section" # self.traceback.print_exc() return None
def _delete_subkey(key0: int, key1: str, key2=""): # from https://stackoverflow.com/questions/38205784/python-how-to-delete-registry-key-and-subkeys-from-hklm-getting-error-5 import winreg as reg if key2 == "": currentkey = key1 else: currentkey = f"{key1}\\{key2}" open_key = reg.OpenKey(key0, currentkey, 0, reg.KEY_ALL_ACCESS) infokey = reg.QueryInfoKey(open_key) for x in range(0, infokey[0]): # NOTE:: This code is to delete the key and all subkeys. # If you just want to walk through them, then # you should pass x to EnumKey. subkey = _winreg.EnumKey(open_key, x) # Deleting the subkey will change the SubKey count used by EnumKey. # We must always pass 0 to EnumKey so we # always get back the new first SubKey. subkey = reg.EnumKey(open_key, 0) try: reg.DeleteKey(open_key, subkey) print(f"Removed {HKEY_CURRENT_USER_text}\\{currentkey}\\{subkey}") except: _delete_subkey(key0, currentkey, subkey) # no extra delete here since each call # to deleteSubkey will try to delete itself when its empty. reg.DeleteKey(open_key, "") open_key.Close() print(f"Removed {HKEY_CURRENT_USER_text}\\{currentkey}")
def delete_sub_key(key0, current_key, arch_key=0): #Code inpsired by Orsiris de Jong's solution https://stackoverflow.com/questions/38205784/python-how-to-delete-registry-key-and-subkeys-from-hklm-getting-error-5 open_key = winreg.OpenKey(key0, current_key, 0, winreg.KEY_ALL_ACCESS | arch_key) info_key = winreg.QueryInfoKey(open_key) for x in range(0, info_key[0]): # NOTE:: This code is to delete the key and all sub_keys. # If you just want to walk through them, then # you should pass x to EnumKey. sub_key = winreg.EnumKey(open_key, x) # Deleting the sub_key will change the sub_key count used by EnumKey. # We must always pass 0 to EnumKey so we # always get back the new first sub_key. sub_key = winreg.EnumKey(open_key, 0) try: winreg.DeleteKey(open_key, sub_key) logger.info("Removed %s\\%s " % (current_key, sub_key)) except OSError: delete_sub_key(key0, "\\".join([current_key, sub_key]), arch_key) # No extra delete here since each call # to delete_sub_key will try to delete itself when its empty. winreg.DeleteKey(open_key, "") open_key.Close() logger.info("Removed %s" % current_key) return
def DeleteKeys(base_key,nodekey): thiskey = winreg.OpenKey(base_key,nodekey) subkeys = [] try: i = 0 while 1: this_key = winreg.EnumKey(thiskey, i) print(this_key) subkeys.append(this_key) i += 1 except WindowsError: pass #print("finished.") if len(subkeys)==0: thisNode = os.path.dirname(nodekey) ks_version = os.path.basename(nodekey) thiskey = winreg.OpenKey(winreg.HKEY_USERS,thisNode) winreg.DeleteKey(thiskey, ks_version) else: if len(subkeys): for elm in subkeys: this_node_new = "%s\%s" % (nodekey,elm) print(this_node_new) DeleteKeys("%s"%this_node_new) print("DeleteKeys: %s "%this_node_new) thisNode = os.path.dirname(nodekey) ks_version = os.path.basename(nodekey) thiskey = winreg.OpenKey(winreg.HKEY_USERS,thisNode) winreg.DeleteKey(thiskey, ks_version)
def unregisterInstallation(keepDesktopShortcut=False): try: winreg.DeleteKeyEx(winreg.HKEY_LOCAL_MACHINE, easeOfAccess.APP_KEY_PATH, winreg.KEY_WOW64_64KEY) easeOfAccess.setAutoStart(winreg.HKEY_LOCAL_MACHINE, False) except WindowsError: pass wsh=_getWSH() desktopPath=os.path.join(wsh.SpecialFolders("AllUsersDesktop"),"NVDA.lnk") if not keepDesktopShortcut and os.path.isfile(desktopPath): try: os.remove(desktopPath) except WindowsError: pass startMenuFolder=getStartMenuFolder() if startMenuFolder: programsPath=wsh.SpecialFolders("AllUsersPrograms") startMenuPath=os.path.join(programsPath,startMenuFolder) if os.path.isdir(startMenuPath): shutil.rmtree(startMenuPath,ignore_errors=True) try: winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\nvda") except WindowsError: pass try: winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\nvda.exe") except WindowsError: pass try: winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE,config.NVDA_REGKEY) except WindowsError: pass unregisterAddonFileAssociation()
def test_safe_mode_blocked_by_policy(self): if platform.system() != 'Windows': return reg_policies = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, "SOFTWARE\\Policies", 0, winreg.KEY_WRITE) reg_mozilla = winreg.CreateKeyEx(reg_policies, "Mozilla", 0, winreg.KEY_WRITE) reg_firefox = winreg.CreateKeyEx(reg_mozilla, "Firefox", 0, winreg.KEY_WRITE) winreg.SetValueEx(reg_firefox, "DisableSafeMode", 0, winreg.REG_DWORD, 1) self.marionette.instance.app_args.append("-safe-mode") self.marionette.quit() self.marionette.start_session() with self.marionette.using_context("chrome"): safe_mode = self.marionette.execute_script(""" Cu.import("resource://gre/modules/Services.jsm"); return Services.appinfo.inSafeMode; """) self.assertFalse(safe_mode, "Safe Mode has been enabled") winreg.CloseKey(reg_firefox) winreg.DeleteKey(reg_mozilla, "Firefox") winreg.CloseKey(reg_mozilla) winreg.DeleteKey(reg_policies, "Mozilla") winreg.CloseKey(reg_policies)
def unregisterCommand(ext, name): import winreg as wr try: ext_key = wr.OpenKey(wr.HKEY_CLASSES_ROOT, '.' + ext) except: return try: auto_file = wr.EnumValue(ext_key, 0)[1] except: return try: auto_key = wr.OpenKey(wr.HKEY_CLASSES_ROOT, auto_file, 0, wr.KEY_ALL_ACCESS) except: return try: shell_key = wr.OpenKey(auto_key, 'shell', 0, wr.KEY_ALL_ACCESS) except: return try: name_key = wr.OpenKey(shell_key, name, 0, wr.KEY_ALL_ACCESS) wr.DeleteKey(name_key, 'command') wr.DeleteKey(name_key, '') except: pass
def deleteSubkey(key0, key1, key2=""): if key2=="": currentkey = key1 else: currentkey = key1+ "\\" +key2 open_key = reg.OpenKey(key0, currentkey ,0,reg.KEY_ALL_ACCESS) infokey = reg.QueryInfoKey(open_key) for x in range(0, infokey[0]): #NOTE:: This code is to delete the key and all subkeys. # If you just want to walk through them, then # you should pass x to EnumKey. subkey = reg.EnumKey(open_key, x) # Deleting the subkey will change the SubKey count used by EnumKey. # We must always pass 0 to EnumKey so we # always get back the new first SubKey. subkey = reg.EnumKey(open_key, 0) try: reg.DeleteKey(open_key, subkey) print("Removed %s\\%s " % ( currentkey, subkey)) except: deleteSubkey( key0, currentkey, subkey ) # no extra delete here since each call #to deleteSubkey will try to delete itself when its empty. reg.DeleteKey(open_key,"") open_key.Close() print("Removed %s" % (currentkey)) return
def delete_tree(root_key, sub_key): ''' Recursively delete subkey (including all subkeys and values). Parameters ---------- root_key : already open key, or one of the predefined HKEY_* constants sub_key : str Subkey to delete. ''' with winreg.OpenKey(root_key, sub_key) as open_key: key_info = dict( zip(('key_count', 'value_count', 'modified'), winreg.QueryInfoKey(open_key))) for i in xrange(0, key_info['key_count']): sub_key_i = winreg.EnumKey(open_key, 0) try: winreg.DeleteKey(open_key, sub_key_i) logging.debug(r'Removed `%s`', sub_key_i) except Exception: # Subkey has child subkeys. delete_tree(open_key, sub_key_i) winreg.DeleteKey(open_key, '') logging.debug('Removed %s', sub_key)
def remove(self): # Removes registry keys cleanly. self.verify_uac() for fext in self.generate_fexts(self.documentObject["exists"]): winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT,fext+"\\shell\\"\ +self.documentObject["name"]+"\\command") winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT,fext+"\\shell\\"\ +self.documentObject["name"])
def delete_reg_key(): try: parent_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"*\\shell") menu_key = winreg.OpenKey(parent_key, app.app_name) # 删除子项 winreg.DeleteKey(menu_key, 'command') # 删除父项 winreg.DeleteKey(parent_key, app.app_name) winreg.CloseKey(parent_key) except Exception as msg: print(msg)
def delreg(): try: key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "*\\shell\\PartExtract-py") winreg.DeleteKey(key, "command") key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "*\\shell") winreg.DeleteKey(key, "PartExtract-py") except: wx.MessageBox(u'右键菜单不存在', u'提示', wx.OK | wx.ICON_ERROR) else: wx.MessageBox(u'成功删除右键菜单', u'提示', wx.OK | wx.ICON_INFORMATION)
def _unbind_reg(): if not ctypes.windll.shell32.IsUserAnAdmin(): ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__ + " --unbind", None, 0) return try: winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Classes\*\shell\APK Parser\command") winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Classes\*\shell\APK Parser") except FileNotFoundError: pass
def main(): with reg.OpenKey(reg.HKEY_LOCAL_MACHINE, sub_key) as base: backup = [] names = set() deletes = [] renames = [] i = 0 while True: try: name = reg.EnumKey(base, i) value = reg.QueryValue(base, name) except OSError: break backup.append((name, value)) core = name.strip() if core in names: deletes.append(name) else: names.add(core) if core in boost: core = ' ' + core if core != name: renames.append((name, core)) i += 1 if deletes or renames: print('Write backup file', backup_filename) with codecs.open(backup_filename, 'w', 'utf_16_le') as backup_file: wr = backup_file.write wr('\ufeff') wr('Windows Registry Editor Version 5.00\r\n\r\n') wr('[{}]\r\n\r\n'.format(key)) for name, value in backup: wr('[{}\\{}]\r\n'.format(key, name)) wr('@="{}"\r\n\r\n'.format(value)) for name in deletes: print('Delete', repr(name)) reg.DeleteKey(base, name) for old_name, new_name in renames: print('Rename', repr(old_name), 'to', repr(new_name)) value = reg.QueryValue(base, old_name) reg.CreateKey(base, new_name) reg.SetValue(base, new_name, reg.REG_SZ, value) reg.DeleteKey(base, old_name) # print('Restart Windows Explorer') # if not os.system('taskkill /F /IM explorer.exe'): # os.system('start explorer.exe') else: print('Nothing to rename')
def _removeKey(path, Type): key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, Type) name = os.path.basename(path) i = name.index(".") if i != -1: name = name[:name.index(".")] name = f"open with {name}" nameKey = winreg.OpenKey(key, name) winreg.DeleteKey(nameKey, "command") winreg.CloseKey(nameKey) winreg.DeleteKey(key, name) winreg.CloseKey(key)
def unregister_shell_extension(name): try: winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, r'exefile\shell\{}\Command'.format(name)) except FileNotFoundError: print("Shell extension '{}' is not registered".format(name)) return winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, r'exefile\shell\{}'.format(name)) print("Unregistered the '{}' shell extension successfully!".format(name))
def set_sleep_clear_key(key, subkey, name, value, value_type, delete_depth=0): try: hkey = winreg.CreateKey(key, subkey) except: common.log("Unable to open key. Likely a permissions error. Exiting") exit(common.ACCESS_DENIED) common.log("Reading existing value from {}\\{}\\{}".format( key_dict[key], subkey, name)) try: # try to read key, will throw WindowsError if key doesn't exist old_value = winreg.QueryValueEx(hkey, name)[0] common.log("Saved original value: {}".format(old_value)) key_existed = True except WindowsError: common.log("Key/value doesn't exist. Will create.") key_existed = False common.log("Setting {} as value".format(value)) try: # try to write to key, will throw WindowsError if permissions are missing winreg.SetValueEx(hkey, name, 0, value_type, value) except WindowsError: common.log( "Unable to write registry key. Likely a permissions error. Exiting" ) winreg.CloseKey(hkey) exit(common.ACCESS_DENIED) time.sleep(2) # Cleanup if key_existed: common.log("Cleaning up, restoring original value") winreg.SetValueEx(hkey, name, 0, value_type, old_value) winreg.CloseKey(hkey) else: if delete_depth == 0: common.log("Cleaning up, deleting {}".format(name)) winreg.DeleteValue(hkey, name) winreg.CloseKey(hkey) else: common.log( "Cleaning up, deleting key to depth {}".format(delete_depth)) winreg.CloseKey(hkey) winreg.DeleteKey(key, subkey) for i in range(-1, -1 * delete_depth, -1): winreg.DeleteKey(key, '\\'.join(subkey.split('\\')[:i])) time.sleep(2)
def unregisterFolderContextMenu(deep=True): """ a deep unregister removes everything, whereas the opposite removes only all your templates """ key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, FOLDER_CONTEXT_MENU_FILETYPE) if deep: winreg.DeleteKey(key, 'Shell/' + FOLDER_CONTEXT_MENU_ANCHOR_ID) try: winreg.DeleteKey(key, FOLDER_CONTEXT_MENU_ID) except Exception: pass
def close(self): self.usystem.usysapp.close() if platform.system() == 'Windows': import winreg osSleep = WindowsInhibitor() osSleep.uninhibit() try: subkey = "*\\shell\\Send to USystem\\command" winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, subkey) subkey = "*\\shell\\Send to USystem" winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, subkey) except: pass sys.exit()
def remove_association(): """Removes the file association. Removes HKEY_CLASSES_ROOT\\LilyPond\\shell\\frescobaldi """ try: key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "LilyPond\\shell") with key: winreg.DeleteKey(key, "frescobaldi\\command") winreg.DeleteKey(key, "frescobaldi") print("* Removed file association") except WindowsError: print("*** Could not remove file association ***")
def unregisterExplorerBackgroundMenu(deep=True): """ a deep unregister removes everything, whereas the opposite removes only all your templates """ key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, EXPLORER_BACKGROUND_MENU_FILETYPE) if deep: winreg.DeleteKey( key, 'background\\Shell\\' + EXPLORER_BACKGROUND_MENU_ANCHOR_ID) try: winreg.DeleteKey(key, EXPLORER_BACKGROUND_MENU_ID) except Exception: pass
def deleteSubkey(hkey, key): open_key = winreg.OpenKey(hkey, key, 0, winreg.KEY_ALL_ACCESS) info_key = winreg.QueryInfoKey(open_key) for x in range(0, info_key[0]): sub_key = winreg.EnumKey(open_key, 0) try: winreg.DeleteKey(open_key, sub_key) print("Removed %s\\%s " % (key, sub_key)) except WindowsError: deleteSubkey(hkey, key + "\\" + sub_key) winreg.DeleteKey(open_key, "") open_key.Close() print("Removed %s" % key)
def del_usb_log(self): self.check_usb() try: for item in self.enum_list1: winreg.DeleteKey(self.key_usb1, str(self.enum_list1)) for item2 in self.enum_list2: winreg.DeleteKey(self.key_usb2, str(self.enum_list2)) except Exception as err: self.output_mon.setText("A error was ocured %s" % err) self.output_mon.setText("The USB log was deleted:") winreg.DeleteKey(self.key_usb1, r"Disk&Ven_Generic&Prod_Flash_Disk&Rev_8.07") winreg.CloseKey(self.key_usb1) winreg.CloseKey(self.key_usb2) winreg.CloseKey()
def delete_mapped_drive(self): """ This method purpose is to delete the current drive instance. It deletes the drive and it's settings from the computer registry and therefor the drive is deleted. :return: None """ cmd = [MappedDrive.PSUBST_PATH + "psubst.bat", self.letter, "/D", "/P"] subprocess.run(cmd) subkey_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\DriveIcons\{0}\DefaultIcon'. \ format(self.letter[:-1]) winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, subkey_path) subkey_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\DriveIcons\{0}'.format(self.letter[:-1]) winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, subkey_path) print("The virtual drive was successfully deleted")
def delete(self, type): try: self.key = winreg.DeleteKey( self.hive, "Software\\Classes\\{type}\\shell\\open\\command".format( type=type)) self.key = winreg.DeleteKey( self.hive, "Software\\Classes\\{type}\\shell\\runas\\command".format( type=type)) winreg.CloseKey(self.key) except Exception: return False else: return True
def remove_action_from(self, filetype, registry_title): reg1 = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Classes\\" + filetype + "\\shell\\", 0, winreg.KEY_SET_VALUE) reg2 = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\Classes\\" + filetype + "\\shell\\" + registry_title, 0, winreg.KEY_SET_VALUE) winreg.DeleteKey(reg2, "command") try: winreg.DeleteKey(reg1, registry_title) except FileNotFoundError: a = 0 winreg.CloseKey(reg1) winreg.CloseKey(reg2)
def edit_reg(keys, key_paths, operation="delete", architecture=64): """creates or deletes registry values""" if (architecture == 32): other_view_flag = winreg.KEY_WOW64_32KEY elif (architecture == 64): other_view_flag = winreg.KEY_WOW64_64KEY else: print("unsupported architecture") return for key in keys: for index, key_path in enumerate(key_paths): try: opened_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path, access=(winreg.KEY_READ | other_view_flag)) if (operation == "delete"): winreg.DeleteKey(opened_key, keys[key]) elif (operation == "create"): winreg.CreateKey(opened_key, keys[key]) else: print( "operation {0} is not supported available operations create, delete" .format(operation)) return print("key: {0} - {1} \t found -> {2}".format( key, index + 1, operation)) except FileNotFoundError: print("key: {0} - {1} \t not found".format(key, index + 1))
def __call__(self, *args, **kwargs): PythonBatchCommandBase.__call__(self, *args, **kwargs) try: self._open_key() winreg.DeleteKey(self.key_handle, "") except Exception as ex: raise