我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用win32con.HKEY_LOCAL_MACHINE。
def CustomOptionHandler(cls, opts): #out=open("c:\\log.txt","w") print "Installing the Pyro %s" % cls._svc_name_ args = raw_input("Enter command line arguments for %s: " % cls._svc_name_) try: createRegistryParameters(cls._svc_name_, args.strip()) except Exception,x: print "Error occured when setting command line args in the registry: ",x try: cls._svc_description_ except LookupError: return key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s" % cls._svc_name_) try: win32api.RegSetValueEx(key, "Description", 0, win32con.REG_SZ, cls._svc_description_); finally: win32api.RegCloseKey(key)
def FindHelpPath(helpFile, helpDesc, searchPaths): # See if the current registry entry is OK import os, win32api, win32con try: key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS) try: try: path = win32api.RegQueryValueEx(key, helpDesc)[0] if FileExists(os.path.join(path, helpFile)): return os.path.abspath(path) except win32api.error: pass # no registry entry. finally: key.Close() except win32api.error: pass for pathLook in searchPaths: if FileExists(os.path.join(pathLook, helpFile)): return os.path.abspath(pathLook) pathLook = os.path.join(pathLook, "Help") if FileExists(os.path.join( pathLook, helpFile)): return os.path.abspath(pathLook) raise error("The help file %s can not be located" % helpFile)
def DumpRegistry(root, level=0): # A recursive dump of the remote registry to test most functions. h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, None) level_prefix = " " * level index = 0 # Enumerate values. while 1: try: name, data, typ = wincerapi.CeRegEnumValue(root, index) except win32api.error: break print "%s%s=%s" % (level_prefix, name, repr(str(data))) index = index+1 # Now enumerate all keys. index=0 while 1: try: name, klass = wincerapi.CeRegEnumKeyEx(root, index) except win32api.error: break print "%s%s\\" % (level_prefix, name) subkey = wincerapi.CeRegOpenKeyEx(root, name) DumpRegistry(subkey, level+1) index = index+1
def _GetServiceShortName(longName): # looks up a services name # from the display name # Thanks to Andy McKay for this code. access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, access) num = win32api.RegQueryInfoKey(hkey)[0] longName = longName.lower() # loop through number of subkeys for x in range(0, num): # find service name, open subkey svc = win32api.RegEnumKey(hkey, x) skey = win32api.RegOpenKey(hkey, svc, 0, access) try: # find display name thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0]) if thisName.lower() == longName: return svc except win32api.error: # in case there is no key called DisplayName pass return None # Open a service given either it's long or short name.
def __FindSvcDeps(findName): if type(findName) is pywintypes.UnicodeType: findName = str(findName) dict = {} k = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services") num = 0 while 1: try: svc = win32api.RegEnumKey(k, num) except win32api.error: break num = num + 1 sk = win32api.RegOpenKey(k, svc) try: deps, typ = win32api.RegQueryValueEx(sk, "DependOnService") except win32api.error: deps = () for dep in deps: dep = dep.lower() dep_on = dict.get(dep, []) dep_on.append(svc) dict[dep]=dep_on return __ResolveDeps(findName, dict)
def DumpPythonRegistry(): try: h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\PythonPath" % sys.winver) except win32api.error: print("The remote device does not appear to have Python installed") return 0 path, typ = wincerapi.CeRegQueryValueEx(h, None) print("The remote PythonPath is '%s'" % (str(path), )) h.Close() return 1
def get_system_path(): # HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment key_string = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' try: keyh = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, key_string , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ) except: return None try: path, type = win32api.RegQueryValueEx(keyh, "PATH") return path except: return None #name=sys.argv[1] #if not os.path.exists(name): #print name, "does not exist!" #sys.exit()
def __init__(self): # variable to write a flat file self.fileHandle = None self.HKEY_CLASSES_ROOT = win32con.HKEY_CLASSES_ROOT self.HKEY_CURRENT_USER = win32con.HKEY_CURRENT_USER self.HKEY_LOCAL_MACHINE = win32con.HKEY_LOCAL_MACHINE self.HKEY_USERS = win32con.HKEY_USERS self.FILE_PATH = "//masblrfs06/karcherarea$/workarea/nishitg/"+ win32api.GetComputerName() self.CONST_OS_SUBKEY = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" self.CONST_PROC_SUBKEY = "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" self.CONST_SW_SUBKEY = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
def getSoftwareList(self): try: hCounter=0 hAttCounter=0 # connecting to the base hHandle = win32api.RegConnectRegistry(None,win32con.HKEY_LOCAL_MACHINE) # getting the machine name and domain name hCompName = win32api.GetComputerName() hDomainName = win32api.GetDomainName() # opening the sub key to get the list of Softwares installed hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE,self.CONST_SW_SUBKEY,0,win32con.KEY_ALL_ACCESS) # get the total no. of sub keys hNoOfSubNodes = win32api.RegQueryInfoKey(hHandle) # delete the entire data and insert it again #deleteMachineSW(hCompName,hDomainName) # browsing each sub Key which can be Applications installed while hCounter < hNoOfSubNodes[0]: hAppName = win32api.RegEnumKey(hHandle,hCounter) hPath = self.CONST_SW_SUBKEY + "\\" + hAppName # initialising hAttCounter hAttCounter = 0 hOpenApp = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE,hPath,0,win32con.KEY_ALL_ACCESS) # [1] will give the no. of attributes in this sub key hKeyCount = win32api.RegQueryInfoKey(hOpenApp) hMaxKeyCount = hKeyCount[1] hSWName = "" hSWVersion = "" while hAttCounter < hMaxKeyCount: hData = win32api.RegEnumValue(hOpenApp,hAttCounter) if hData[0]== "DisplayName": hSWName = hData[1] self.preparefile("SW Name",hSWName) elif hData[0]== "DisplayVersion": hSWVersion = hData[1] self.preparefile("SW Version",hSWVersion) hAttCounter = hAttCounter + 1 #if (hSWName !=""): #insertMachineSW(hCompName,hDomainName,hSWName,hSWVersion) hCounter = hCounter + 1 except: self.preparefile("Exception","In exception in getSoftwareList")
def getProgramsMenuPath(): """Get the path to the Programs menu. Probably will break on non-US Windows. @returns: the filesystem location of the common Start Menu->Programs. """ if not platform.isWinNT(): return "C:\\Windows\\Start Menu\\Programs" keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders' hShellFolders = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, keyname, 0, win32con.KEY_READ) return win32api.RegQueryValueEx(hShellFolders, 'Common Programs')[0]
def getProgramFilesPath(): """Get the path to the Program Files folder.""" keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' currentV = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, keyname, 0, win32con.KEY_READ) return win32api.RegQueryValueEx(currentV, 'ProgramFilesDir')[0]
def RemoveSourceFromRegistry(appName, eventLogType = "Application"): """Removes a source of messages from the event log. """ # Delete our key try: win32api.RegDeleteKey(win32con.HKEY_LOCAL_MACHINE, \ "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName)) except win32api.error, exc: if exc.winerror != winerror.ERROR_FILE_NOT_FOUND: raise
def FormatMessage( eventLogRecord, logType="Application" ): """Given a tuple from ReadEventLog, and optionally where the event record came from, load the message, and process message inserts. Note that this function may raise win32api.error. See also the function SafeFormatMessage which will return None if the message can not be processed. """ # From the event log source name, we know the name of the registry # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName) # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) try: dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";") # Win2k etc appear to allow multiple DLL names data = None for dllName in dllNames: try: # Expand environment variable strings in the message DLL path name, # in case any are there. dllName = win32api.ExpandEnvironmentStrings(dllName) dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE) try: data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts) finally: win32api.FreeLibrary(dllHandle) except win32api.error: pass # Not in this DLL - try the next if data is not None: break finally: win32api.RegCloseKey(handle) return data or u'' # Don't want "None" ever being returned.
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 LocatePythonServiceExe(exeName = None): if not exeName and hasattr(sys, "frozen"): # If py2exe etc calls this with no exeName, default is current exe. return sys.executable # Try and find the specified EXE somewhere. If specifically registered, # use it. Otherwise look down sys.path, and the global PATH environment. if exeName is None: if os.path.splitext(win32service.__file__)[0].endswith("_d"): exeName = "PythonService_d.exe" else: exeName = "PythonService.exe" # See if it exists as specified if os.path.isfile(exeName): return win32api.GetFullPathName(exeName) baseName = os.path.splitext(os.path.basename(exeName))[0] try: exeName = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\%s\\%s" % (baseName, sys.winver)) if os.path.isfile(exeName): return exeName raise RuntimeError("The executable '%s' is registered as the Python " \ "service exe, but it does not exist as specified" \ % exeName) except win32api.error: # OK - not there - lets go a-searchin' for path in [sys.prefix] + sys.path: look = os.path.join(path, exeName) if os.path.isfile(look): return win32api.GetFullPathName(look) # Try the global Path. try: return win32api.SearchPath(None, exeName)[0] except win32api.error: msg = "%s is not correctly registered\nPlease locate and run %s, and it will self-register\nThen run this service registration process again." % (exeName, exeName) raise error(msg)
def LocateSpecificServiceExe(serviceName): # Given the name of a specific service, return the .EXE name _it_ uses # (which may or may not be the Python Service EXE hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0, win32con.KEY_ALL_ACCESS) try: return win32api.RegQueryValueEx(hkey, "ImagePath")[0] finally: hkey.Close()
def InstallPythonClassString(pythonClassString, serviceName): # Now setup our Python specific entries. if pythonClassString: key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\PythonClass" % serviceName) try: win32api.RegSetValue(key, None, win32con.REG_SZ, pythonClassString); finally: win32api.RegCloseKey(key) # Utility functions for Services, to allow persistant properties.
def SetServiceCustomOption(serviceName, option, value): try: serviceName = serviceName._svc_name_ except AttributeError: pass key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName) try: if type(value)==type(0): win32api.RegSetValueEx(key, option, 0, win32con.REG_DWORD, value); else: win32api.RegSetValueEx(key, option, 0, win32con.REG_SZ, value); finally: win32api.RegCloseKey(key)
def GetServiceCustomOption(serviceName, option, defaultValue = None): # First param may also be a service class/instance. # This allows services to pass "self" try: serviceName = serviceName._svc_name_ except AttributeError: pass key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName) try: try: return win32api.RegQueryValueEx(key, option)[0] except win32api.error: # No value. return defaultValue finally: win32api.RegCloseKey(key)
def _find_localserver_exe(mustfind): if not sys.platform.startswith("win32"): return sys.executable if pythoncom.__file__.find("_d") < 0: exeBaseName = "pythonw.exe" else: exeBaseName = "pythonw_d.exe" # First see if in the same directory as this .EXE exeName = os.path.join( os.path.split(sys.executable)[0], exeBaseName ) if not os.path.exists(exeName): # See if in our sys.prefix directory exeName = os.path.join( sys.prefix, exeBaseName ) if not os.path.exists(exeName): # See if in our sys.prefix/pcbuild directory (for developers) if "64 bit" in sys.version: exeName = os.path.join( sys.prefix, "PCbuild", "amd64", exeBaseName ) else: exeName = os.path.join( sys.prefix, "PCbuild", exeBaseName ) if not os.path.exists(exeName): # See if the registry has some info. try: key = "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % sys.winver path = win32api.RegQueryValue( win32con.HKEY_LOCAL_MACHINE, key ) exeName = os.path.join( path, exeBaseName ) except (AttributeError,win32api.error): pass if not os.path.exists(exeName): if mustfind: raise RuntimeError("Can not locate the program '%s'" % exeBaseName) return None return exeName
def getRegistryParameters(servicename): key=win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\"+servicename) try: try: (commandLine, regtype) = win32api.RegQueryValueEx(key,pyroArgsRegkeyName) return commandLine except: pass finally: key.Close() createRegistryParameters(servicename, pyroArgsRegkeyName) return ""
def createRegistryParameters(servicename, parameters): newkey=win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\"+servicename,0,win32con.KEY_ALL_ACCESS) try: win32api.RegSetValueEx(newkey, pyroArgsRegkeyName, 0, win32con.REG_SZ, parameters) finally: newkey.Close()
def __init__(self, logCallback): MSstore = r"Software\Microsoft\SystemCertificates" GPstore = r"Software\Policy\Microsoft\SystemCertificates" self.regKeys = { "CU_STORE": [reg.HKEY_CURRENT_USER, MSstore], "LM_STORE": [reg.HKEY_LOCAL_MACHINE, MSstore], "USER_STORE": [reg.HKEY_USERS, MSstore], "CU_POLICY_STORE": [reg.HKEY_CURRENT_USER, GPstore], "LM_POLICY_STORE": [reg.HKEY_LOCAL_MACHINE, GPstore] } self.logCallback = logCallback
def _watch_thread_dispatcher(self): MSstore = r"Software\Microsoft\SystemCertificates" GPstore = r"Software\Policy\Microsoft\SystemCertificates" regKeys = { "CU_STORE": [win32con.HKEY_CURRENT_USER, MSstore], "LM_STORE": [win32con.HKEY_LOCAL_MACHINE, MSstore], "USER_STORE": [win32con.HKEY_USERS, MSstore], "CU_POLICY_STORE": [win32con.HKEY_CURRENT_USER, GPstore], "LM_POLICY_STORE": [win32con.HKEY_LOCAL_MACHINE, GPstore] } watchKeys = self.database.get_watch_keys() for regKey in watchKeys: self._log("Dispatcher preparing watch thread for key: %s" % regKey, messageType="DEBUG") key = regKey.split("/") storeName = key.pop(0) additionalValue = "\\%s" % "\\".join(key) keystore = regKeys[storeName] keyName = keystore[1] + additionalValue t = threading.Thread(target=self._watch_thread, args=(keystore[0], keyName, regKey, self._watch_thread_callback,)) self.watchThreads.append(t) self._log("Thread prepared.", messageType="DEBUG") self._log("Launching %d threads..." % len(self.watchThreads), messageType="DEBUG") for t in self.watchThreads: t.start() self._log("Dispatcher completed.", messageType="DEBUG") return
def DumpPythonRegistry(): try: h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\PythonPath" % sys.winver) except win32api.error: print "The remote device does not appear to have Python installed" return 0 path, typ = wincerapi.CeRegQueryValueEx(h, None) print "The remote PythonPath is '%s'" % (str(path), ) h.Close() return 1
def _GetRegistryValue(key, val, default = None): # val is registry value - None for default val. try: hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, key) return win32api.RegQueryValueEx(hkey, val)[0] except win32api.error: try: hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, key) return win32api.RegQueryValueEx(hkey, val)[0] except win32api.error: return default
def ListAllHelpFiles(): ret = [] ret = _ListAllHelpFilesInRoot(win32con.HKEY_LOCAL_MACHINE) # Ensure we don't get dups. for item in _ListAllHelpFilesInRoot(win32con.HKEY_CURRENT_USER): if item not in ret: ret.append(item) return ret
def FindTabNanny(): try: return __import__("tabnanny") except ImportError: pass # OK - not in the standard library - go looking. filename = "tabnanny.py" try: path = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % (sys.winver)) except win32api.error: print "WARNING - The Python registry does not have an 'InstallPath' setting" print " The file '%s' can not be located" % (filename) return None fname = os.path.join(path, "Tools\\Scripts\\%s" % filename) try: os.stat(fname) except os.error: print "WARNING - The file '%s' can not be located in path '%s'" % (filename, path) return None tabnannyhome, tabnannybase = os.path.split(fname) tabnannybase = os.path.splitext(tabnannybase)[0] # Put tab nanny at the top of the path. sys.path.insert(0, tabnannyhome) try: return __import__(tabnannybase) finally: # remove the tab-nanny from the path del sys.path[0]
def FindTabNanny(): try: return __import__("tabnanny") except ImportError: pass # OK - not in the standard library - go looking. filename = "tabnanny.py" try: path = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % (sys.winver)) except win32api.error: print("WARNING - The Python registry does not have an 'InstallPath' setting") print(" The file '%s' can not be located" % (filename)) return None fname = os.path.join(path, "Tools\\Scripts\\%s" % filename) try: os.stat(fname) except os.error: print("WARNING - The file '%s' can not be located in path '%s'" % (filename, path)) return None tabnannyhome, tabnannybase = os.path.split(fname) tabnannybase = os.path.splitext(tabnannybase)[0] # Put tab nanny at the top of the path. sys.path.insert(0, tabnannyhome) try: return __import__(tabnannybase) finally: # remove the tab-nanny from the path del sys.path[0]
def FormatMessage( eventLogRecord, logType="Application" ): """Given a tuple from ReadEventLog, and optionally where the event record came from, load the message, and process message inserts. Note that this function may raise win32api.error. See also the function SafeFormatMessage which will return None if the message can not be processed. """ # From the event log source name, we know the name of the registry # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName) # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) try: dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";") # Win2k etc appear to allow multiple DLL names data = None for dllName in dllNames: try: # Expand environment variable strings in the message DLL path name, # in case any are there. dllName = win32api.ExpandEnvironmentStrings(dllName) dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE) try: data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts) finally: win32api.FreeLibrary(dllHandle) except win32api.error: pass # Not in this DLL - try the next if data is not None: break finally: win32api.RegCloseKey(handle) return data or '' # Don't want "None" ever being returned.
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 as 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 as exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise