def modifyReg(): run = win32api.RegOpenKey( win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, win32con.KEY_ALL_ACCESS) try: SysinfY2X = win32api.RegQueryValueEx(run, "SysinfY2X") if "SysinfY2X.db" in SysinfY2X[0]: win32api.RegDeleteValue(run, "SysinfY2X") else: pass except win32api.error: print "no registry entry" finally: win32api.RegCloseKey(run) Advanced = win32api.RegOpenKey( win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced", 0, win32con.KEY_ALL_ACCESS) try: hidden = win32api.RegQueryValueEx(Advanced, "Hidden") if 2 == hidden[0]: win32api.RegSetValueEx(Advanced, "Hidden", 0, win32con.REG_DWORD, 1) else: print "Modified" except win32api.error: print "no registry entry" finally: win32api.RegCloseKey(Advanced)
def UnregisterHelpFile(helpFile, helpDesc=None): """Unregister a help file in the registry. helpFile -- the base name of the help file. helpDesc -- A description for the help file. If None, the helpFile param is used. """ key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS) try: try: win32api.RegDeleteValue(key, helpFile) except win32api.error, exc: import winerror if exc.winerror != winerror.ERROR_FILE_NOT_FOUND: raise finally: win32api.RegCloseKey(key) # Now de-register with Python itself. if helpDesc is None: helpDesc = helpFile try: win32api.RegDeleteKey( GetRootKey(), BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc) except win32api.error, exc: import winerror if exc.winerror != winerror.ERROR_FILE_NOT_FOUND: raise
def delete_value(hive, key, vname=None, use_32bit_registry=False): """ Delete a registry value entry or the default value for a key. Args: hive (str): The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. vname (str): The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be deleted. use_32bit_registry (bool): Deletes the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. Return: bool: True if successful, otherwise False Usage: .. code-block:: python import salt.utils.win_reg winreg.delete_value(hive='HKLM', key='SOFTWARE\\SaltTest', vname='version') """ local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError("Invalid Hive: {0}".format(local_hive)) access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS handle = None try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) win32api.RegDeleteValue(handle, local_vname) broadcast_change() return True except win32api.error as exc: if exc.winerror == 2: return None raise finally: if handle: win32api.RegCloseKey(handle)
def delete_value(self, value_name): """delete a value item""" key = self.get_key() win32api.RegDeleteValue(key, value_name) key.close() return True
def deleteReg(self): # 异常处理 try: key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, self.KeyName, 0, win32con.KEY_ALL_ACCESS) win32api.RegDeleteValue(key, self.name) win32api.RegCloseKey(key) except Exception as e: pass
def delete_value(hive, key, vname=None, use_32bit_registry=False): ''' Delete a registry value entry or the default value for a key. :param str hive: The name of the hive. Can be one of the following - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC :param str key: The key (looks like a path) to the value name. :param str vname: The value name. These are the individual name/data pairs under the key. If not passed, the key (Default) value will be deleted. :param bool use_32bit_registry: Deletes the 32bit portion of the registry on 64bit installations. On 32bit machines this is ignored. :return: Returns True if successful, None if the value didn't exist, and False if unsuccessful :rtype: bool CLI Example: .. code-block:: bash salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version' ''' local_hive = _to_unicode(hive) local_key = _to_unicode(key) local_vname = _to_unicode(vname) registry = Registry() try: hkey = registry.hkeys[local_hive] except KeyError: raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive)) access_mask = registry.registry_32[ use_32bit_registry] | win32con.KEY_ALL_ACCESS try: handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask) win32api.RegDeleteValue(handle, local_vname) win32api.RegCloseKey(handle) broadcast_change() return True except Exception as exc: # pylint: disable=E0602 if exc.winerror == 2: return None else: log.error(exc, exc_info=True) log.error('Hive: %s', local_hive) log.error('Key: %s', local_key) log.error('ValueName: %s', local_vname) log.error('32bit Reg: %s', use_32bit_registry) return False
def remove_key_from_reg(id_of_instance): try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, constants.SUBMODULE_KEY, 0, win32con.KEY_ALL_ACCESS) if key: win32api.RegDeleteValue(key, str(id_of_instance)) except Exception as e: pass
def remove_python_to_autorun(): print('remove auto-run.') runpath = "Software\\Microsoft\\Windows\\CurrentVersion\\Run" hKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, runpath, 0, win32con.KEY_ALL_ACCESS) try: win32api.RegDeleteValue(hKey, 'MessageNotifierService') except: pass win32api.RegCloseKey(hKey)
def close(self): try: logger.info(u'关闭开机自启...') key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, self.key_name, 0, win32con.KEY_ALL_ACCESS) win32api.RegDeleteValue(key, self.app_name) win32api.RegCloseKey(key) except: logger.warn(u'关闭开机自启失败')
def setup_set_value(self): try: win32api.RegDeleteValue( win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, r"Software\winsys", 0, win32con.KEY_ALL_ACCESS), "winsys4") except win32api.error as error: errno, errctx, errmsg = error.args if errno == 2: pass else: raise
def delfile2autorun(self, path): runpath = "Software\Microsoft\Windows\CurrentVersion\Run" hKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, runpath, 0, win32con.KEY_SET_VALUE) win32api.RegCreateKey(hKey, 'Python') path = os.path.abspath(path) if False == os.path.isfile(path): return False (filepath, filename) = os.path.split(path) win32api.RegDeleteValue(hKey, filename) win32api.RegCloseKey(hKey) return True
def delete_registry(path, valuename): reg_root = win32con.HKEY_LOCAL_MACHINE reg_path = path reg_flags = win32con.WRITE_OWNER | win32con.KEY_WOW64_64KEY | win32con.KEY_ALL_ACCESS try: # 删除value key = win32api.RegOpenKeyEx(reg_root, reg_path, 0, reg_flags) win32api.RegDeleteValue(key, valuename) win32api.RegCloseKey(key) return True except: return False
def unRegisterBootUp(self): if FileUtil.getFileName(self.exePath) == "python.exe": return try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, self.bootUpkey, 0, win32con.KEY_ALL_ACCESS) # self.name 是值的名称 win32api.RegDeleteValue(key, self.name) win32api.RegCloseKey(key) print 'unRegister boot success!' except: print 'unRegister boot up key error !'
def __delitem__(self, key): # Delete a string value or a subkey, depending on the type try: item = self[key] except: return # Silently ignore bad keys itemtype = type(item) if itemtype is str: win32api.RegDeleteValue(self.keyhandle, key) elif isinstance(item, RegistryDict): # Delete everything in the subkey, then the subkey itself item.clear() win32api.RegDeleteKey(self.keyhandle, key) else: raise ValueError, "Unknown item type in RegistryDict"
def qxqd(self): zdynames = os.path.basename(__file__) # 当前文件名的名称如:newsxiao.py name = os.path.splitext(zdynames)[0] # 获得文件名的前部分,如:newsxiao path = os.path.abspath(os.path.dirname(__file__)) + '\\' + "runpytask.vbs" # 要添加的exe完整路径如: # 注册表项名 KeyName = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' # 异常处理 try: key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, KeyName, 0, win32con.KEY_ALL_ACCESS) win32api.RegDeleteValue(key, "runpytask") win32api.RegCloseKey(key) self.statusbar.showMessage('开机启动删除成功') self.taskboot.setText("开机启动") except: self.statusbar.showMessage('开机启动删除失败')
def clear_win_http_settings(): # XXX: # setting a system proxy in Windows writes to the registry and that # key needs to be deleted as said on the reference page, but a user # might have set a "real" proxy using the same WinHTTPSettings ... import win32api import win32con opened_key = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings'\ '\Connections', 0, win32con.KEY_ALL_ACCESS) win32api.RegDeleteValue(opened_key, 'WinHttpSettings') ERROR_SUCCESS = 0 error_code = win32api.GetLastError() if error_code != ERROR_SUCCESS: print 'win32 error code %d', error_code, \ win32api.FormatMessage(error_code)
def AutoRun(self, switch='open', # 开:open # 关:close current_file='love', # 获得文件名的前部分,如:newsxiao abspath=os.path.abspath(os.path.dirname(__file__))): # 当前文件路径: """ :param switch: 注册表开启、关闭自启动 :param zdynames: 当前文件名 :param current_file: 获得文件名的前部分 :param abspath: 当前文件路径 :return: """ print(current_file) print(abspath) path = os.path.join(abspath, current_file + '.exe') # 要添加的exe完整路径如: print(path) # 注册表项名 KeyName = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' judge_key = self.Judge_Key(reg_root=win32con.HKEY_CURRENT_USER, reg_path=KeyName, # 键的路径 key_name=current_file) key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, KeyName, 0, win32con.KEY_SET_VALUE) if switch == "open": # 异常处理 try: if judge_key == 0: print("已经开启了,无需再开启") elif judge_key == 1: win32api.RegSetValueEx(key, current_file, 0, win32con.REG_SZ, path) win32api.RegCloseKey(key) print('开机自启动添加成功!') except: print('添加失败') elif switch == "close": try: if judge_key == 0: win32api.RegDeleteValue(key, current_file) # 删除值 win32api.RegCloseKey(key) print('成功删除键!') elif judge_key == 1: print("键不存在") elif judge_key == 2: print("权限不足") else: print("出现错误") except: print('删除失败')
def setUp(self): # Wipe the current settings to normalize. try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, chrome_control._CHROME_FRAME_KEY, 0, win32con.KEY_SET_VALUE) except Exception: return values = (chrome_control._PREREAD_VALUE, chrome_control._PREREAD_PERCENTAGE_VALUE, chrome_control._PREREAD_SIZE_VALUE, chrome_control._PREREAD_STEP_VALUE) for value in values: try: win32api.RegDeleteValue(key, value) except Exception: pass
def GetValue(self, key, defaultValue=None): """Return a value from the registry, returning the default value if a value cannot be found and destroying invalid values if any are found.""" try: value, type = win32api.RegQueryValueEx(self.key, key) except: cx_Logging.Debug( "Getting default for session key %s\\%s. Value=\"%s\"", self.baseName, key, defaultValue) return defaultValue try: returnValue = eval(str(value)) cx_Logging.Debug("Getting session key %s\\%s. Value=\"%s\"", self.baseName, key, returnValue) return returnValue except: win32api.RegDeleteValue(self.key, key) cx_Logging.Debug( "Getting default for session key %s\\%s. Value=\"%s\"", self.baseName, key, defaultValue) return defaultValue
def add2boot(self, startup): try: # "注册到启动项" path = os.path.normpath(sys.argv[0]) subKey = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Run' hKey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, subKey, 0, win32con.KEY_ALL_ACCESS) # win32api.RegQueryValueEx(hKey, 'BingWallpaper') # 判断项值是否存在 if startup: try: win32api.RegQueryValueEx(hKey, 'BingWallpaper') # 判断项值是否存在 except: win32api.RegSetValueEx(hKey, 'BingWallpaper', 0, win32con.REG_SZ, path) else: try: win32api.RegDeleteValue(hKey, 'BingWallpaper') except: pass except: logging.exception( time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) finally: win32api.RegCloseKey(hKey)
def start_up(): APP_NAME = 'NetTool' # 要添加的项值名称 app_path = os.path.split( os.path.realpath(__file__))[0] + '\\NetTool.exe' # 要添加的路径 # 注册表项名 APP_KEY_NAME = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run' # 异常处理 try: APP_KEY = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, APP_KEY_NAME, 0, win32con.KEY_ALL_ACCESS) if usr['startup']: win32api.RegSetValueEx(APP_KEY, APP_NAME, 0, win32con.REG_SZ, f'"{app_path}"') write_log('开机启动设置成功') write_log('开机启动路径:' + app_path, 0) else: win32api.RegDeleteValue(APP_KEY, APP_NAME) write_log('开机启动已经移除') win32api.RegCloseKey(APP_KEY) except: mBox.showinfo(title='开机启动', message='添加开机启动失败!')
def persist(self, persist): """Add/Remove persistence to reboots by adding a registry key entry which autoruns a vbs script on boot. The vbs script is required in order to run this component silently and is created/removed during this method. This method is automatically called to add persistence during initialisation and remove persistence during the kill routine. @param persist: whether to add or remove persistence """ dir_name = os.path.dirname(os.path.abspath(__file__)) vbs_script_file = os.path.join(dir_name, "data.vbs") if persist: if not os.path.exists(vbs_script_file): curr_file = win32api.GetModuleFileName(0) target_exe = os.path.basename(curr_file) if target_exe == "python.exe": logging.debug( "Running as python script, adding args to persistence script." ) curr_file = win32api.GetCommandLine() vbs_script = open(vbs_script_file, "w") # Windows doesn't like it when something being executed using the autorun registry key being used here # modifies the registry, so the '-r' argument is passed to this script to disable the persistence # adding routine on bootup. vbs_script.write( 'Dim WShell\nSet WShell = CreateObject("Wscript.Shell")\nWShell.Run "{0} -r", 0\nSet WShell = Nothing' .format(curr_file)) # nopep8 vbs_script.close() startup_script = "wscript \"{0}\"".format(vbs_script_file) curr_script = None try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, self.PERSISTENCE_KEY, 0, win32con.KEY_QUERY_VALUE) curr_script = win32api.RegQueryValueEx( key, self.REG_KEY_ENTRY) win32api.RegCloseKey(key) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e)) # if curr_script is None (no value) or incorrect, replace with correct one if startup_script != curr_script: logging.debug( "Adding {0} to run on startup...".format(curr_file)) logging.debug( "Script executed by registry key on boot: {0}".format( startup_script)) try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, self.PERSISTENCE_KEY, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, self.REG_KEY_ENTRY, 0, win32con.REG_SZ, "{0}".format(startup_script)) win32api.RegCloseKey(key) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e)) else: logging.debug("Removing from startup...") if os.path.exists(vbs_script_file): logging.debug("Removing vbs script.") try: os.remove(vbs_script_file) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e)) try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, self.PERSISTENCE_KEY, 0, win32con.KEY_SET_VALUE) win32api.RegDeleteValue(key, self.REG_KEY_ENTRY) win32api.RegCloseKey(key) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e))
def remove_key_from_reg(): key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, SUBMODULE_KEY, 0, win32con.KEY_ALL_ACCESS) if key: win32api.RegDeleteValue(key, str(ID_OF_INSTANCE))
def del_value(self, key, value): try: win32api.RegDeleteValue(key, value) except: print('Value {} not Exist'.format(value))
#index+= 1 # print "delete key: ",subsubKey DeleteTree(hkey, subsubKey) except Exception, err: # print "enum key except",err flag_continue = False index = 0 flag_continue = True while flag_continue: try: (value, _, _) = win32api.RegEnumValue(hkey, index) # don't increment because it's a enum and we delete the key so the index is always 0 # index+= 1 # print "delete value: ",value win32api.RegDeleteValue(hkey, value) except Exception, err: # print "enum value except",err flag_continue = False win32api.RegCloseKey(hkey) if deleteRoot: win32api.RegDeleteKey(key, subkey) def TreeSearchExpression(hive, subpath, motif): path = hive+"\\"+subpath hkey = None res = None index = 0
def delete(self, valueName): return Api.RegDeleteValue(self.hKey, valueName)
def __delitem__(self, item): win32api.RegDeleteValue(self.keyhandle, str(item))
def deleteValue(self, name): key = self.__getKey() win32api.RegDeleteValue(key, name) key.close()
import win32api import win32con key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\\Scooter Software\\Beyond Compare 4', 0, win32con.KEY_ALL_ACCESS) # value = win32api.RegQueryValue(key,'') # value = win32api.RegQueryValueEx(key,'CacheID') win32api.RegDeleteValue(key, 'CacheID') # print(value) win32api.RegCloseKey(key)