def get_winroot_from_registry(): """Get the Windows directory, e.g. c:\WINDOWS, from the registry, or None if not found or error.""" if HAVE_WIN32_REGISTRY == 0: return None try: # SystemRoot is found here on win9x machines topkey = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion") path, typ = QueryValueEx(topkey, 'SystemRoot') return path except: pass try: # On NT/2k/etc., SystemRoot is under 'Windows NT' instead topkey = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion") path, typ = QueryValueEx(topkey, 'SystemRoot') return path except: pass # maybe it doesn't exist under some versions of win32 return None
def lookup_reg(key, valname=None, scope=None): ''' Look up a key/value name in the Windows registry. valname: value name. If unspecified, the default value for the key is used. scope: optionally specify scope for registry lookup, this can be a sequence of scopes to look up in order. Default (CURRENT_USER, LOCAL_MACHINE). ''' try: from _winreg import HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, \ QueryValueEx, OpenKey except ImportError: return None if scope is None: scope = (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE) elif not isinstance(scope, (list, tuple)): scope = (scope,) for s in scope: try: val = QueryValueEx(OpenKey(s, key), valname)[0] # never let a Unicode string escape into the wild return encoding.tolocal(val.encode('UTF-8')) except EnvironmentError: pass
def get_prog_command(progid): """use the program id to find out program path params: progid - program id in registry """ open_command = None edit_command = None sub_key = '\\'.join([progid, 'shell', 'edit', 'command']) try: key = OpenKey(HKEY_CLASSES_ROOT, sub_key) edit_command = QueryValueEx(key, None)[0] except WindowsError: pass sub_key = '\\'.join([progid, 'shell', 'open', 'command']) try: key = OpenKey(HKEY_CLASSES_ROOT, sub_key) open_command = QueryValueEx(key, None)[0] except WindowsError: pass if not (open_command or edit_command): return None return edit_command or open_command
def check_registry_key(java_key): """ Method checks for the java in the registry entries. """ # Added KEY_WOW64_64KEY, KEY_ALL_ACCESS. This lets 32bit python access # registry keys of 64bit Application on Windows supporting 64 bit. try: from _winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, \ QueryValueEx, KEY_WOW64_64KEY, KEY_ALL_ACCESS except: from winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, \ QueryValueEx, KEY_WOW64_64KEY, KEY_ALL_ACCESS path = None try: a_reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) r_key = OpenKey(a_reg, java_key, 0, KEY_WOW64_64KEY + KEY_ALL_ACCESS) for i_cnt in range(1024): current_version = QueryValueEx(r_key, "CurrentVersion") if current_version is not None: key = OpenKey(r_key, current_version[0]) if key is not None: path = QueryValueEx(key, "JavaHome") return path[0] except Exception: UcsWarning("Not able to access registry.") return None
def search_name(locals, prog_path): """use the prog_path to find out the program display name locals: -- (main_key, sub_key) prog_path: -- program execute path return prog_name """ for local in locals: key = OpenKey(*local) key_no = QueryInfoKey(key)[0] for index in xrange(key_no): key_name = EnumKey(key, index) app_key = OpenKey(key, key_name) for value_name in ('InstallLocation', 'LocationRoot', 'UninstallString'): try: value_data = QueryValueEx(app_key, value_name)[0] if value_data and (value_data.startswith(prog_path) or prog_path.startswith(value_data)): prog_name = QueryValueEx(app_key, 'DisplayName')[0] return prog_name except WindowsError: pass return None
def get_config(): show_taskbaricon = True hgighlight_taskbaricon = True version2cmenu = False try: from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx hkey = OpenKey(HKEY_CURRENT_USER, r'Software\TortoiseHg') t = ('1', 'True') try: show_taskbaricon = QueryValueEx(hkey, 'ShowTaskbarIcon')[0] in t except EnvironmentError: pass try: hgighlight_taskbaricon = QueryValueEx(hkey, 'HighlightTaskbarIcon')[0] in t except EnvironmentError: pass # Upgrade user's context menu, once per major release try: version2cmenu = QueryValueEx(hkey, 'ContextMenuVersion')[0] == '2' except EnvironmentError: pass try: if not version2cmenu: from _winreg import CreateKey, SetValueEx, REG_SZ try: promoted = QueryValueEx(hkey, 'PromotedItems')[0] except EnvironmentError: promoted = '' plist = [i.strip() for i in promoted.split(',')] hkey = CreateKey(HKEY_CURRENT_USER, r'Software\TortoiseHg') if u'log' in plist: idx = plist.index(u'log') plist[idx] = u'workbench' SetValueEx(hkey, 'PromotedItems', 0, REG_SZ, ','.join(plist)) SetValueEx(hkey, 'ContextMenuVersion', 0, REG_SZ, '2') except EnvironmentError: pass except (ImportError, WindowsError): pass return (show_taskbaricon, hgighlight_taskbaricon)
def getCustomLogDir(self): if platform == 'win32': from _winreg import OpenKey, EnumKey, QueryValueEx, HKEY_LOCAL_MACHINE aKey = OpenKey( HKEY_LOCAL_MACHINE, r"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" ) try: i = 0 while True: asubkey = OpenKey(aKey, EnumKey(aKey, i)) try: if QueryValueEx( asubkey, "Publisher")[0] == "Frontier Developments": custpath = join( QueryValueEx(asubkey, "InstallLocation")[0], "Products") if isdir(custpath): for d in listdir(custpath): if d.startswith("FORC-FDEV-D-1") and isdir( join(custpath, d, "Logs")): asubkey.Close() aKey.Close() return join(custpath, d, "Logs") except: pass asubkey.Close() i += 1 except: aKey.Close() return None
def __get_binary_path(name): binary = '' if sys.platform == 'linux2': binary = Popen('which %s' % name, stdout=PIPE, shell=True).stdout.read().strip() elif sys.platform == 'win32': if name == 'soffice': key = OpenKey(HKEY_LOCAL_MACHINE, (r'SOFTWARE\OpenOffice.org' r'\Layers\OpenOffice.org\3'), 0, KEY_ALL_ACCESS) sub_key = QueryValueEx(key, "OFFICEINSTALLLOCATION")[0] binary = os.path.join(sub_key, 'program', 'soffice.exe') elif name == 'firefox' or name == 'thunderbird': key = OpenKey(HKEY_LOCAL_MACHINE, r'Software\Mozilla\Mozilla ' + name.capitalize(), 0, KEY_ALL_ACCESS) sub_key = QueryValueEx(key, "CurrentVersion")[0] key = OpenKey( HKEY_LOCAL_MACHINE, r'Software\Mozilla\Mozilla ' + name.capitalize() + '\\' + sub_key + '\\Main', 0, KEY_ALL_ACCESS) binary = QueryValueEx(key, "PathToExe")[0] if binary: return binary else: print "Binary not found." return False
def default_browser_command(): if WIN32: if six.PY2: from _winreg import (CloseKey, ConnectRegistry, HKEY_CLASSES_ROOT, # pylint: disable=import-error,no-name-in-module HKEY_CURRENT_USER, OpenKey, QueryValueEx) else: from winreg import (CloseKey, ConnectRegistry, HKEY_CLASSES_ROOT, # pylint: disable=import-error,no-name-in-module HKEY_CURRENT_USER, OpenKey, QueryValueEx) ''' Tries to get default browser command, returns either a space delimited command string with '%1' as URL placeholder, or empty string. ''' browser_class = 'Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice' try: reg = ConnectRegistry(None,HKEY_CURRENT_USER) key = OpenKey(reg, browser_class) value, t = QueryValueEx(key, 'ProgId') CloseKey(key) CloseKey(reg) reg = ConnectRegistry(None,HKEY_CLASSES_ROOT) key = OpenKey(reg, '%s\\shell\\open\\command' % value) path, t = QueryValueEx(key, None) except WindowsError: # pylint: disable=undefined-variable # logger.warn(e) traceback.print_exc() return '' finally: CloseKey(key) CloseKey(reg) return path else: default_browser = webbrowser.get() return default_browser.name + " %1"
def get_current_wallpaper(win): """ Try to get the current wallpaper image path. :param win: Windows version (Major, Minor). :type win: Tuple of Integers :returns: Wallpaper image path if it can find it. :rtype: String """ wallpaper = None wallpaper_path = '' key = None default_entry = None reg_location = None LOGGER.debug('get_current_wallpaper: ' + str(win)) if win[0] == 5: # XP == 5,1 XP64 == 5,2 reg_location = __WIN_XP_REG elif win[0] == 6: reg_location = __WIN_VISTA7_REG if win[1] == 0: # Vista default_entry = r'Microsoft\Windows\Themes\TranscodedWallpaper.jpg' elif win[1] == 1: # Windows 7 default_entry = r'Microsoft\Windows\Themes\TranscodedWallpaper.jpg' elif win[1] == 2: # Windows 8 default_entry = r'Microsoft\Windows\Themes\TranscodedWallpaper' try: # Try the defualt location if available. if default_entry and ('APPDATA' in os.environ): wallpaper_path = os.path.join(os.environ['APPDATA'], default_entry) LOGGER.debug('Accessing: ' + wallpaper_path) # Get current current_wallpaper from registry if needed. if wallpaper_path and os.path.exists(wallpaper_path): wallpaper = wallpaper_path # We might have the default wallpaper now, but let's try # replace it with the current one... if reg_location: LOGGER.debug('reg_location: ' + str(reg_location)) key = OpenKey(HKEY_CURRENT_USER, reg_location) LOGGER.debug('key: ' + str(key) + ' open!') wallpaper_path = QueryValueEx(key, 'Wallpaper')[0] LOGGER.debug('keyval: ' + str(wallpaper_path)) if wallpaper_path.count('%') > 1: index_start = wallpaper_path.find('%') index_end = wallpaper_path.find('%', index_start + 1) env = wallpaper_path[index_start + 1:index_end] end = wallpaper_path[index_end + 2:] wallpaper_path = os.path.join(os.getenv(env), end) LOGGER.debug('keyval2: ' + str(wallpaper_path)) if (wallpaper_path) and len(wallpaper_path): wallpaper = wallpaper_path except (ValueError, IOError, OSError) as excp: LOGGER.exception('get_current_wallpaper exception: {0!s}'.format(excp)) if key is not None: CloseKey(key) return wallpaper
def check_system_path(): hive = HKEY_LOCAL_MACHINE key = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' with OpenKey(hive, key, 0, KEY_READ) as regkey: path, type = QueryValueEx(regkey, 'PATH') path = [p.strip().rstrip('\\') for p in path.split(';') if p.strip()] for p in path: if os.path.isfile(os.path.join(p, 'sadm.py')): eprintc('\nSadm is in the system path. It should be removed because the system path setting may conflict with the user path setting.', WARNING_COLOR) break
def __init__(self): with OpenKey(HKEY_CURRENT_USER, steam_key) as key: steam_path, type = QueryValueEx(key, steam_path_name) # steam path stored with / as seperator, change to use \ and normalize (should already be normalized, but just to make sure steam_path = os.path.normpath(steam_path.replace("/", "\\")) user_name, type = QueryValueEx(key, user_name_name) self.steam_path = steam_path # self.user_name = user_name # last known display user name assert os.path.isdir(steam_path) self.config = vdf.VDF(os.path.join(steam_path, "config\\config.vdf")) self.appinfo = None
def __init__(self): with OpenKey(HKEY_CURRENT_USER, steam_key) as key: steam_path, type = QueryValueEx(key, steam_path_name) #steam path stored with / as seperator, change to use \ and normalize (should already be normalized, but just to make sure steam_path = os.path.normpath(steam_path.replace('/', '\\')) user_name, type = QueryValueEx(key, user_name_name) self.steam_path = steam_path # self.user_name = user_name #last known display user name assert (os.path.isdir(steam_path)) self.config = vdf.VDF(os.path.join(steam_path, 'config\\config.vdf')) self.appinfo = None
def get_nsis_path(): bin_name = "makensis.exe" from _winreg import HKEY_LOCAL_MACHINE as HKLM from _winreg import KEY_READ, KEY_WOW64_32KEY, OpenKey, QueryValueEx try: nsisreg = OpenKey(HKLM, "Software\\NSIS", 0, KEY_READ | KEY_WOW64_32KEY) if QueryValueEx(nsisreg, "VersionMajor")[0] >= 3: return "{}\\{}".format(QueryValueEx(nsisreg, "")[0], bin_name) else: raise Exception("You must install NSIS 3 or later.") except WindowsError: return bin_name
def get_latest_windows_sdk(): """The Windows SDK that ships with VC++ 9.0 is not new enough to include schannel support. So we need to check the OS to see if a newer Windows SDK is available to link to. This is only run on Windows if using Python 2.7. """ if not is_win or not is_27: return [] from _winreg import ConnectRegistry, OpenKey, EnumKey, QueryValueEx, HKEY_LOCAL_MACHINE installed_sdks = {} key_path = "SOFTWARE\\Wow6432Node\\Microsoft\\Microsoft SDKs\\Windows" if is_x64 else \ "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows" try: with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hklm: with OpenKey(hklm, key_path) as handler: for i in range(1024): try: asubkey_name=EnumKey(handler, i) with OpenKey(handler, asubkey_name) as asubkey: location = QueryValueEx(asubkey, "InstallationFolder") if not location or not os.path.isdir(location[0]): continue version = QueryValueEx(asubkey, "ProductVersion") if not version: continue installed_sdks[version[0].lstrip('v')] = location[0] except EnvironmentError: break except EnvironmentError: print("Warning - build may fail: No Windows SDK found.") return [] installed_versions = sorted([LooseVersion(k) for k in installed_sdks.keys()]) if installed_versions[-1] < LooseVersion("8.1"): print("Warning - build may fail: Cannot find Windows SDK 8.1 or greater.") return [] lib_path = os.path.join(installed_sdks[installed_versions[-1].vstring], "lib") sdk_path = os.path.join(lib_path, os.listdir(lib_path)[-1], "um", 'x64' if is_x64 else 'x86') if not os.path.isdir(sdk_path): print("Warning - build may fail: Windows SDK v{} not found at path {}.".format( installed_versions[-1].vstring, sdk_path)) else: print("Adding Windows SDK v{} to search path, installed at {}".format( installed_versions[-1].vstring, sdk_path)) return [sdk_path]
def getInstalledSoftwareFromReg(): softs = set() r = wmi.Registry() keyPath = r"Software\Microsoft\Windows\CurrentVersion\Uninstall" result, names = r.EnumKey(hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=keyPath) return reg = re.compile('^hotfix|kb(\d+)|service pack', re.I) for subkey in names: try: path = keyPath + "\\" + subkey key = OpenKey(HKEY_LOCAL_MACHINE, path, 0, KEY_ALL_ACCESS) try: temp = QueryValueEx(key, 'DisplayName') display = str(temp[0]) if display == None or display == '' or reg.search( display) <> None: continue softs.add(display) except: pass except: pass return sorted(list(softs))
def extend_user_env_windows(name, value, mode): '''NEVER call this function directly. Use the safer and platform-neutral 'extend_user_env' instead.''' # !! We're messing with the Windows Registry here, edit with care !! import _winreg from _winreg import OpenKey, QueryValueEx, SetValueEx, CloseKey user_env = OpenKey(_winreg.HKEY_CURRENT_USER, 'Environment', 0, _winreg.KEY_ALL_ACCESS) try: old_value, old_value_type = QueryValueEx(user_env, name) assert old_value_type in (_winreg.REG_SZ, _winreg.REG_EXPAND_SZ) except WindowsError: old_value, old_value_type = '', _winreg.REG_SZ if not old_value or mode == 'o': new_value = value elif mode == 'a': new_value = os.pathsep.join((old_value, value)) else: # mode == 'p' new_value = os.pathsep.join((value, old_value)) if old_value_type == _winreg.REG_SZ and value.find('%') != -1: new_value_type = _winreg.REG_EXPAND_SZ else: new_value_type = old_value_type SetValueEx(user_env, name, 0, new_value_type, new_value) CloseKey(user_env)
def get_installed_products(): """ Enumerate all installed products. """ products = {} hkey_products = OpenKey(HKEY_LOCAL_MACHINE, PRODUCTS_KEY, 0, KEY_ALL_ACCESS) try: product_index = 0 while True: product_guid = EnumKey(hkey_products, product_index) hkey_product_properties = OpenKey( hkey_products, product_guid + r'\InstallProperties', 0, KEY_ALL_ACCESS) try: value = QueryValueEx(hkey_product_properties, 'DisplayName')[0] except WindowsError as oXcpt: if oXcpt.winerror != 2: raise value = '<unknown>' CloseKey(hkey_product_properties) products[product_guid] = value product_index += 1 except WindowsError as oXcpt: if oXcpt.winerror != 259: print(oXcpt.strerror + '.', 'error', oXcpt.winerror) CloseKey(hkey_products) print('Installed products:') for product_key in sorted(products.keys()): print(transpose_guid(product_key), '=', products[product_key]) print() return products
def query(key, subkey, what): try: (value, type) = QueryValueEx(key, subkey) except WindowsError, e: if e.winerror == 2: # not found return None raise DistutilsSetupError("I could not read %s from the registry.\n%r" % (what, e))
def change_key(cd_key): cd_key = cd_key.upper() key_pattern = re.compile(("[A-Z0-9]{5}-" "[A-Z0-9]{5}-" "[A-Z0-9]{5}-" "[A-Z0-9]{5}-" "[A-Z0-9]{5}")) if not key_pattern.match(cd_key): print( "The CD Key seems invalid.\nPlease input a key in the form " "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX") return False cd_key = cd_key.replace("-", "") reg_key = OpenKey(HKEY_LOCAL_MACHINE, (r'SOFTWARE\Microsoft\Windows NT' '\CurrentVersion\WPAEvents'), 0, KEY_ALL_ACCESS) try: _ = QueryValueEx(reg_key, 'OOBETimer')[0] # noqa DeleteValue(reg_key, 'OOBETimer') except WindowsError: pass win = wmi.WMI() ret_code = None for instance in win.win32_WindowsProductActivation(): ret_code = instance.SetProductKey(cd_key)[0] return not ret_code
def _get_effective_state_index(): """ Get the state file index that's currently in use - deprecated :return: index of the current effective state file """ hKey = OpenKey(HKEY_LOCAL_MACHINE, BITSStateFile.REG_BITS_KEY) return QueryValueEx(hKey, BITSStateFile.REG_STATE_INDEX_VALUE)[0]
def CheckRegistryKey(javaKey): from _winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx path = None try: aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) rk = OpenKey(aReg, javaKey) for i in range(1024): currentVersion = QueryValueEx(rk, "CurrentVersion") if currentVersion != None: key = OpenKey(rk, currentVersion[0]) if key != None: path = QueryValueEx(key, "JavaHome") return path[0] except Exception, err: WriteUcsWarning("Not able to access registry.") return None
def get_ue4_root(project_name): """Figure out which UE4 engine source is associated with 'project_name'.""" with open(project_name) as f: project = json.load(f) if not project['EngineAssociation'].startswith("{"): print "\nProject is using stock engine. With this tool you can only build from Engine source.\nPlease switch engine versions in %s" % project_name sys.exit(1) if sys.platform == 'win32': from _winreg import OpenKey, QueryValueEx, HKEY_CURRENT_USER key_name = r'SOFTWARE\Epic Games\Unreal Engine\Builds' key = OpenKey(HKEY_CURRENT_USER, key_name) try: ue4_root, reg_type = QueryValueEx(key, project['EngineAssociation']) except WindowsError as e: print "Can't figure out UE4 root. Please specify explicitly." print e print "Engine '%s' from project file was probably not found in registry key '%s'" % ( project['EngineAssociation'], key_name) sys.exit(1) elif sys.platform == 'darwin': raise RuntimeError("Please implmement me!") else: raise RuntimeError("Build platform %s not supported.", sys.platform) return ue4_root
def get_password(self, service, username): """Get password of the username for the service """ from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx try: # fetch the password key = r'Software\%s\Keyring' % service hkey = OpenKey(HKEY_CURRENT_USER, key) password_base64 = QueryValueEx(hkey, username)[0] # decode with base64 password_encrypted = password_base64.decode("base64") # decrypted the password password = self.crypt_handler.decrypt(password_encrypted) except EnvironmentError: password = None return password
def get_installed_products(): """ Enumerate all installed products. """ products = {} hkey_products = OpenKey(HKEY_LOCAL_MACHINE, PRODUCTS_KEY, 0, KEY_ALL_ACCESS) try: product_index = 0 while True: product_guid = EnumKey(hkey_products, product_index) hkey_product_properties = OpenKey( hkey_products, product_guid + r'\InstallProperties', 0, KEY_ALL_ACCESS) try: value = QueryValueEx(hkey_product_properties, 'DisplayName')[0] except WindowsError, exception: if exception.winerror != 2: raise value = '<unknown>' CloseKey(hkey_product_properties) products[product_guid] = value product_index += 1 except WindowsError, exceptione: if exceptione.winerror != 259: print exceptione.strerror + '.', 'error', exceptione.winerror
def detectPort(): try: if not isRunning(AceStuff.ace): logger.error("Couldn't detect port! Ace Engine is not running?") clean_proc(); sys.exit(1) except AttributeError: logger.error("Ace Engine is not running!") clean_proc(); sys.exit(1) try: from _winreg import ConnectRegistry, OpenKey, QueryValueEx, HKEY_CURRENT_USER except: from winreg import ConnectRegistry, OpenKey, QueryValueEx, HKEY_CURRENT_USER reg = ConnectRegistry(None, HKEY_CURRENT_USER) try: key = OpenKey(reg, 'Software\AceStream') except: logger.error("Can't find AceStream!") clean_proc(); sys.exit(1) else: engine = QueryValueEx(key, 'EnginePath') AceStuff.acedir = os.path.dirname(engine[0]) try: gevent.sleep(AceConfig.acestartuptimeout) AceConfig.ace['aceAPIport'] = open(AceStuff.acedir + '\\acestream.port', 'r').read() logger.info("Detected ace port: %s" % AceConfig.ace['aceAPIport']) except IOError: logger.error("Couldn't detect port! acestream.port file doesn't exist?") clean_proc(); sys.exit(1)
def detect_windows_program(self, program): entry = self.windows_register.get(program, None) try: key = OpenKey(HKEY_CURRENT_USER, entry, 0, KEY_READ) return QueryValueEx(key, 'Path')[0] except WindowsError: return None
def set_user_env(reg, parent=None): """Set HKCU (current user) environment variables""" reg = listdict2envdict(reg) types = dict() key = OpenKey(HKEY_CURRENT_USER, "Environment") for name in reg: try: _x, types[name] = QueryValueEx(key, name) except WindowsError: types[name] = REG_EXPAND_SZ key = OpenKey(HKEY_CURRENT_USER, "Environment", 0, KEY_SET_VALUE) for name in reg: SetValueEx(key, name, 0, types[name], reg[name]) try: from win32gui import SendMessageTimeout from win32con import (HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG) SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 5000) except ImportError: QMessageBox.warning( parent, _("Warning"), _("Module <b>pywin32 was not found</b>.<br>" "Please restart this Windows <i>session</i> " "(not the computer) for changes to take effect."))
def getExeList(self, justpath=False): """ Get a list of installed executables. getExeList() --> List of installed EXEs """ reg = self.__c.StdRegProv # Using StdRegProv Class for registry l = [] if justpath is False: # Part based on Android-scripting Engine code with few modifications keyPath = r"Software\Microsoft\Windows\CurrentVersion\Uninstall" result, names = reg.EnumKey(2147483650, keyPath) count = 0 while count < len(names): try: path = keyPath + "\\" + names[count] key = OpenKey(HKEY_LOCAL_MACHINE, path, 0) temp = QueryValueEx(key, 'DisplayName') displayname = str(temp[0]) displayversion = '' try: temp = QueryValueEx(key, 'DisplayVersion') displayversion = str(temp[0]) except: pass l.append((displayname, displayversion)) count += 1 except WindowsError: l.append((names[count], )) count += 1 continue return l else: # Shows only the exec's paths keyPath = r"Software\Microsoft\Windows\CurrentVersion\App Paths" result, names = reg.EnumKey(2147483650, keyPath) count = 0 while count < len(names): try: path = keyPath + "\\" + names[count] key = OpenKey(HKEY_LOCAL_MACHINE, path, 0) temp = QueryValueEx(key, 'Path') tPath = str(temp[0] + '\\' + names[count]) l.append(tPath) count += 1 except WindowsError: l.append(names[count]) count += 1 continue return l
def activate(self, event): self.Unbind(wx.EVT_IDLE) if platform=='win32': from _winreg import OpenKey, QueryValueEx, HKEY_CURRENT_USER, REG_SZ, REG_EXPAND_SZ progs=getenv("PROGRAMFILES", '\\').decode('mbcs') for i in listdir(progs): if i.lower().startswith("x-plane") and isdir(join(progs, i, "Custom Scenery")): folder=join(progs, i) break else: folder=getenv("USERPROFILE", '\\').decode('mbcs') # fallback try: handle=OpenKey(HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders') (v,t)=QueryValueEx(handle, 'Desktop') handle.Close() if t==REG_EXPAND_SZ: dirs=v.rstrip('\0').decode('mbcs').strip().split('\\') for i in range(len(dirs)): if dirs[i][0]==dirs[i][-1]=='%': dirs[i]=getenv(dirs[i][1:-1],dirs[i]).decode('mbcs') v='\\'.join(dirs) if t in [REG_SZ,REG_EXPAND_SZ] and isdir(v): folder=desktop=v for i in listdir(desktop): if i.lower().startswith("x-plane") and isdir(join(desktop, i, "Custom Scenery")): folder=join(desktop, i) break except: pass else: try: home=expanduser('~').decode(getfilesystemencoding() or 'utf-8') # Unicode so paths listed as unicode desktop=join(home, "Desktop") except: home=desktop=u'/' for i in listdir(desktop): if i.lower().startswith("x-plane") and isdir(join(desktop, i, "Custom Scenery")): folder=join(desktop, i) break else: for i in listdir(home): if i.lower().startswith("x-plane") and isdir(join(home, i, "Custom Scenery")): folder=join(home, i) break else: folder=home if not self.folder: style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER if 'DD_DIR_MUST_EXIST' in dir(wx): style|=wx.DD_DIR_MUST_EXIST if not platform.startswith('linux'): dlg=wx.DirDialog(self.dummy, 'Choose the folder that contains the aircraft or scenery that you want to publish', folder, style) else: # displayed in title on linux dlg=wx.DirDialog(self.dummy, 'Select aircraft or scenery folder', folder, style) if dlg.ShowModal()!=wx.ID_OK: exit(1) self.folder = dlg.GetPath() publish(unicodeify(self.folder), self) exit(0)
def get_env(name, user=True): root, subkey = env_keys(user) key = OpenKey(root, subkey, 0, KEY_READ) try: value, _ = QueryValueEx(key, name) except WindowsError: return '' return value
def check_registry_key(java_key): """ Method checks for the java in the registry entries. """ from _winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx path = None try: a_reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) rk = OpenKey(a_reg, java_key) for i in range(1024): current_version = QueryValueEx(rk, "CurrentVersion") if current_version != None: key = OpenKey(rk, current_version[0]) if key != None: path = QueryValueEx(key, "JavaHome") return path[0] except Exception: write_imc_warning("Not able to access registry.") return None
def create_tcp_port(self, port_name, ip_address, port=9100): base_path = (r'SYSTEM\ControlSet001\Control' r'\Print\Monitors\Standard TCP/IP Port\Ports') reg_key = OpenKey(HKEY_LOCAL_MACHINE, base_path, 0, KEY_ALL_ACCESS) try: _ = QueryValueEx(reg_key, 'StatusUpdateEnabled')[0] # noqa except WindowsError: SetValueEx(reg_key, 'StatusUpdateEnabled', 0, REG_DWORD, 1) try: _ = QueryValueEx(reg_key, 'StatusUpdateInterval')[0] # noqa except WindowsError: SetValueEx(reg_key, 'StatusUpdateInterval', 0, REG_DWORD, 10) CloseKey(reg_key) try: _ = OpenKey(HKEY_LOCAL_MACHINE, r'{base}\{port}'.format(base=base_path, port=port_name), 0, KEY_ALL_ACCESS) # noqa print "There is already a port named :" + port_name return False except WindowsError: try: reg_key = OpenKey(HKEY_LOCAL_MACHINE, base_path, 0, KEY_ALL_ACCESS) CreateKey(reg_key, port_name) CloseKey(reg_key) reg_key = OpenKey( HKEY_LOCAL_MACHINE, base_path + '\\' + port_name, r'{base}\{port}'.format(base=base_path, port=port_name), 0, KEY_ALL_ACCESS) SetValueEx(reg_key, 'Protocol', 0, REG_DWORD, 1) SetValueEx(reg_key, 'Version', 0, REG_DWORD, 1) SetValueEx(reg_key, 'HostName', 0, REG_SZ, '') SetValueEx(reg_key, 'IPAddress', 0, REG_SZ, ip_address) SetValueEx(reg_key, 'HWAddress', 0, REG_SZ, '') SetValueEx(reg_key, 'PortNumber', 0, REG_DWORD, port) SetValueEx(reg_key, 'SNMP Community', 0, REG_SZ, 'public') SetValueEx(reg_key, 'SNMP Enabled', 0, REG_DWORD, 1) SetValueEx(reg_key, 'SNMP Index', 0, REG_DWORD, 1) result = self.__restart_win_service('Spooler') return result except Exception: # noqa return False
def getEditorCommand(self): """Return the editor command""" editor = self.options.get('editor') if win32 and editor is None: # Find editor application based on mime type and extension content_type = self.metadata.get('content_type') extension = self.options.get('extension') logger.debug('Have content type: %r, extension: %r', content_type, extension) if content_type: # Search registry for the extension by MIME type try: key = 'MIME\\Database\\Content Type\\%s' % content_type key = OpenKeyEx(HKEY_CLASSES_ROOT, key) extension, nil = QueryValueEx(key, 'Extension') logger.debug('Registry has extension %r for ' 'content type %r', extension, content_type) except EnvironmentError: pass if extension is None: url = self.metadata['url'] dot = url.rfind('.') if dot != -1 and dot > url.rfind('/'): extension = url[dot:] logger.debug('Extracted extension from url: %r', extension) classname = editor = None if extension is not None: try: key = OpenKeyEx(HKEY_CLASSES_ROOT, extension) classname, nil = QueryValueEx(key, None) logger.debug('ClassName for extension %r is: %r', extension, classname) except EnvironmentError: classname = None if classname is not None: try: # Look for Edit action in registry key = OpenKeyEx(HKEY_CLASSES_ROOT, classname+'\\Shell\\Edit\\Command') editor, nil = QueryValueEx(key, None) logger.debug('Edit action for %r is: %r', classname, editor) except EnvironmentError: pass if classname is not None and editor is None: logger.debug('Could not find Edit action for %r. ' 'Brute-force enumeration.', classname) # Enumerate the actions looking for one # starting with 'Edit' try: key = OpenKeyEx(HKEY_CLASSES_ROOT, classname+'\\Shell') index = 0 while True: try: subkey = EnumKey(key, index) index += 1 if str(subkey).lower().startswith('edit'): subkey = OpenKeyEx(key, subkey + '\\Command') editor, nil = QueryValueEx(subkey, None) if editor is None: continue logger.debug('Found action %r for %r. ' 'Command will be: %r', subkey, classname, editor) except EnvironmentError: break except EnvironmentError: pass if classname is not None and editor is None: try: # Look for Open action in registry key = OpenKeyEx(HKEY_CLASSES_ROOT, classname+'\\Shell\\Open\\Command') editor, nil = QueryValueEx(key, None) logger.debug('Open action for %r has command: %r. ', classname, editor) except EnvironmentError: pass if editor is None: try: nil, editor = FindExecutable(self.content_file, '') logger.debug('Executable for %r is: %r. ', self.content_file, editor) except pywintypes.error: pass # Don't use IE as an "editor" if editor is not None and editor.find('\\iexplore.exe') != -1: logger.debug('Found iexplore.exe. Skipping.') editor = None if editor is not None: return ExpandEnvironmentStrings(editor) if editor is None: fatalError('No editor was found for that object.\n' 'Specify an editor in the configuration file:\n' '(%s)' % self.config.path) return editor
def getEditorCommand(self): """Return the editor command""" editor = self.options.get('editor') if win32 and editor is None: from _winreg import HKEY_CLASSES_ROOT, OpenKeyEx, \ QueryValueEx, EnumKey from win32api import FindExecutable import pywintypes # Find editor application based on mime type and extension content_type = self.metadata.get('content_type') extension = self.options.get('extension') if content_type: # Search registry for the extension by MIME type try: key = 'MIME\\Database\\Content Type\\%s' % content_type key = OpenKeyEx(HKEY_CLASSES_ROOT, key) extension, nil = QueryValueEx(key, 'Extension') except EnvironmentError: pass if extension is None: url = self.metadata['url'] dot = url.rfind('.') if dot != -1 and dot > url.rfind('/'): extension = url[dot:] if extension is not None: try: key = OpenKeyEx(HKEY_CLASSES_ROOT, extension) classname, nil = QueryValueEx(key, None) except EnvironmentError: classname = None if classname is not None: try: # Look for Edit action in registry key = OpenKeyEx(HKEY_CLASSES_ROOT, classname+'\\Shell\\Edit\\Command') editor, nil = QueryValueEx(key, None) except EnvironmentError: pass if editor is None: # Enumerate the actions looking for one # starting with 'Edit' try: key = OpenKeyEx(HKEY_CLASSES_ROOT, classname+'\\Shell') index = 0 while 1: try: subkey = EnumKey(key, index) index += 1 if str(subkey).lower().startswith('edit'): subkey = OpenKeyEx(key, subkey + '\\Command') editor, nil = QueryValueEx(subkey, None) else: continue except EnvironmentError: break except EnvironmentError: pass if editor is None: try: # Look for Open action in registry key = OpenKeyEx(HKEY_CLASSES_ROOT, classname+'\\Shell\\Open\\Command') editor, nil = QueryValueEx(key, None) except EnvironmentError: pass if editor is None: try: nil, editor = FindExecutable(self.content_file, '') except pywintypes.error: pass # Don't use IE as an "editor" if editor is not None and editor.find('\\iexplore.exe') != -1: editor = None if not editor and not win32 and has_tk(): from tkSimpleDialog import askstring editor = askstring('Zope External Editor', 'Enter the command to launch the default editor') if not editor: sys.exit(0) self.config.set('general', 'editor', editor) self.config.save() if editor is not None: return editor else: fatalError('No editor was found for that object.\n' 'Specify an editor in the configuration file:\n' '(%s)' % self.config.path)
def get_user_path(): hive = HKEY_CURRENT_USER key = 'Environment' with OpenKey(hive, key, 0, KEY_READ) as regkey: path, type = QueryValueEx(regkey, 'PATH') return [p.strip().rstrip('\\') for p in path.split(';') if p.strip()]
debugging = False enabled = True localonly = False includepaths = [] excludepaths = [] try: from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx from win32api import GetTickCount CACHE_TIMEOUT = 5000 try: hkey = OpenKey(HKEY_CURRENT_USER, r"Software\TortoiseHg") enabled = QueryValueEx(hkey, 'EnableOverlays')[0] in ('1', 'True') localonly = QueryValueEx(hkey, 'LocalDisksOnly')[0] in ('1', 'True') incs = QueryValueEx(hkey, 'IncludePath')[0] excs = QueryValueEx(hkey, 'ExcludePath')[0] debugging = QueryValueEx(hkey, 'OverlayDebug')[0] in ('1', 'True') for p in incs.split(';'): path = p.strip() if path: includepaths.append(path) for p in excs.split(';'): path = p.strip() if path: excludepaths.append(path) except EnvironmentError: pass except ImportError: from time import time as GetTickCount CACHE_TIMEOUT = 5.0
debugging = False enabled = True localonly = False includepaths = [] excludepaths = [] try: from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx from win32api import GetTickCount CACHE_TIMEOUT = 5000 try: hkey = OpenKey(HKEY_CURRENT_USER, r"Software\TortoiseHg") enabled = QueryValueEx(hkey, "EnableOverlays")[0] in ("1", "True") localonly = QueryValueEx(hkey, "LocalDisksOnly")[0] in ("1", "True") incs = QueryValueEx(hkey, "IncludePath")[0] excs = QueryValueEx(hkey, "ExcludePath")[0] debugging = QueryValueEx(hkey, "OverlayDebug")[0] in ("1", "True") for p in incs.split(";"): path = p.strip() if path: includepaths.append(path) for p in excs.split(";"): path = p.strip() if path: excludepath.append(path) except EnvironmentError: pass except ImportError: from time import time as GetTickCount