def _check_reg(self, sub_key): # see comments in check_httpd(), above, for why this routine exists and what it's doing. try: # Note that we HKCR is a union of HKLM and HKCR (with the latter # overriding the former), so reading from HKCR ensures that we get # the value if it is set in either place. See als comments below. hkey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, sub_key) args = _winreg.QueryValue(hkey, '').split() _winreg.CloseKey(hkey) # In order to keep multiple checkouts from stepping on each other, we simply check that an # existing entry points to a valid path and has the right command line. if (len(args) == 2 and self._filesystem.exists(args[0]) and args[0].endswith('perl.exe') and args[1] == '-wT'): return True except WindowsError as error: # WindowsError is not defined on non-Windows platforms - pylint: disable=undefined-variable if error.errno != errno.ENOENT: raise # The key simply probably doesn't exist. # Note that we write to HKCU so that we don't need privileged access # to the registry, and that will get reflected in HKCR when it is read, above. cmdline = self._path_from_chromium_base('third_party', 'perl', 'perl', 'bin', 'perl.exe') + ' -wT' hkey = _winreg.CreateKeyEx(_winreg.HKEY_CURRENT_USER, 'Software\\Classes\\' + sub_key, 0, _winreg.KEY_WRITE) _winreg.SetValue(hkey, '', _winreg.REG_SZ, cmdline) _winreg.CloseKey(hkey) return True
def set_upgrade_envvar(self): if not os.environ.get("OPENSVC_AGENT_UPGRADE"): return path = r"SYSTEM\CurrentControlSet\Services\%s\Environment" % WINSVCNAME reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) key = winreg.CreateKeyEx(reg, path, 0, winreg.KEY_WRITE) try: winreg.SetValue(key, "OPENSVC_AGENT_UPGRADE", winreg.REG_SZ, "1") except EnvironmentError: raise ex.excError("failed to set OPENSVC_AGENT_UPGRADE=1 in %s" % path) winreg.CloseKey(key) winreg.CloseKey(reg)
def unset_upgrade_envvar(self): path = r"SYSTEM\CurrentControlSet\Services\%s\Environment" % WINSVCNAME reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) try: key = winreg.OpenKey(reg, path, 0, winreg.KEY_WRITE) winreg.DeleteValue(key, "OPENSVC_AGENT_UPGRADE") winreg.CloseKey(key) except Exception as exc: if hasattr(exc, "errno") and getattr(exc, "errno") == 2: # key does not exist return raise finally: winreg.CloseKey(reg)
def __init__( self, vmx, user='', password='', vmrun='', debug=False ): self.VM_FILE = vmx # TODO strict censor? self.VM_ADMIN = user self.VM_PASS = password self.DEBUG = debug if vmrun != '': self.VMRUN_PATH = vmrun else: if os.sys.platform == 'darwin': self.provider = 'fusion' self.VMRUN_PATH = '/Applications/VMware\ Fusion.app/Contents/Library/vmrun' elif os.sys.platform == "win32": # get vmrun.exe's full path via registry from six.moves import winreg as _winreg reg = _winreg.ConnectRegistry( None, _winreg.HKEY_LOCAL_MACHINE ) try: # Known registry key location in Windows 10 rh = _winreg.OpenKey( reg, r'SOFTWARE\WOW6432Node\VMware, Inc.\VMware Workstation' ) try: vw_dir = _winreg.QueryValueEx( rh, 'InstallPath' )[0] finally: _winreg.CloseKey( rh ) except WindowsError: # Previously used registry key location rh = _winreg.OpenKey( reg, r'SOFTWARE\VMware, Inc.\VMware Workstation' ) try: vw_dir = _winreg.QueryValueEx( rh, 'InstallPath' )[0] finally: _winreg.CloseKey( rh ) finally: reg.Close() self.provider = 'ws' if vw_dir != '': self.VMRUN_PATH = vw_dir + 'vmrun.exe' else: self.provider = 'ws' if os.environ.has_key("PATH"): for path in os.environ["PATH"].split(os.pathsep): tmp_file = path + os.sep + "vmrun" if os.path.exists(tmp_file): self.VMRUN_PATH = tmp_file break vmrun_path = getattr(self, 'VMRUN_PATH', None) if vmrun_path is None: raise RuntimeError('Could not locate vmrun executable!')
def _visual_compiler(output, version): 'version have to be 8.0, or 9.0 or... anything .0' from six.moves import winreg try: hKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion") winreg.QueryValueEx(hKey, "ProgramFilesDir (x86)") is_64bits = True except EnvironmentError: is_64bits = False finally: winreg.CloseKey(hKey) if is_64bits: key_name = r'SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VC7' else: key_name = r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\SxS\VC7' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_name) winreg.QueryValueEx(key, version) installed_version = Version(version).major(fill=False) compiler = "Visual Studio" output.success("Found %s %s" % (compiler, installed_version)) return compiler, installed_version except EnvironmentError: return None
def find_windows_10_sdk(): """finds valid Windows 10 SDK version which can be passed to vcvarsall.bat (vcvars_command)""" # uses the same method as VCVarsQueryRegistry.bat from six.moves import winreg # @UnresolvedImport hives = [ (winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Wow6432Node'), (winreg.HKEY_CURRENT_USER, r'SOFTWARE\Wow6432Node'), (winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE'), (winreg.HKEY_CURRENT_USER, r'SOFTWARE') ] for key, subkey in hives: try: hkey = winreg.OpenKey(key, r'%s\Microsoft\Microsoft SDKs\Windows\v10.0' % subkey) installation_folder, _ = winreg.QueryValueEx(hkey, 'InstallationFolder') if os.path.isdir(installation_folder): include_dir = os.path.join(installation_folder, 'include') for sdk_version in os.listdir(include_dir): if os.path.isdir(os.path.join(include_dir, sdk_version)) and sdk_version.startswith('10.'): windows_h = os.path.join(include_dir, sdk_version, 'um', 'Windows.h') if os.path.isfile(windows_h): return sdk_version except EnvironmentError: pass finally: winreg.CloseKey(hkey) return None
def win32FontDirectory(): """ Return the user-specified font directory for Win32. This is looked up from the registry key:: \\\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\Fonts If the key is not found, $WINDIR/Fonts will be returned. """ try: from six.moves import winreg except ImportError: pass # Fall through to default else: try: user = winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) try: try: return winreg.QueryValueEx(user, 'Fonts')[0] except OSError: pass # Fall through to default finally: winreg.CloseKey(user) except OSError: pass # Fall through to default return os.path.join(os.environ['WINDIR'], 'Fonts')
def SetEnv(name, value): key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment', 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value) winreg.CloseKey(key) win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment') return value
def _delete_key_if_empty(self, service): key_name = self._key_for_service(service) key = winreg.OpenKey( winreg.HKEY_CURRENT_USER, key_name, 0, winreg.KEY_ALL_ACCESS) try: winreg.EnumValue(key, 0) return except WindowsError: pass winreg.CloseKey(key) # it's empty; delete everything while key_name != 'Software': parent, sep, base = key_name.rpartition('\\') key = winreg.OpenKey( winreg.HKEY_CURRENT_USER, parent, 0, winreg.KEY_ALL_ACCESS) winreg.DeleteKey(key, base) winreg.CloseKey(key) key_name = parent
def set_registry(keys): mask = winreg.KEY_WOW64_64KEY | winreg.KEY_ALL_ACCESS if is_64bit( ) else winreg.KEY_ALL_ACCESS for key_name, values in keys.items(): try: key = winreg.CreateKeyEx(values[0], values[1], 0, mask) winreg.SetValueEx(key, values[2], 0, values[3], values[4]) winreg.CloseKey(key) logger.info("Registry: Successfully modified {key} key.".format( key=key_name)) except OSError: logger.exception( "Registry: Unable to modify {key} key.".format(key=key_name))
def _system_registry_key(key, subkey, query): from six.moves import winreg # @UnresolvedImport try: hkey = winreg.OpenKey(key, subkey) except (OSError, WindowsError): # Raised by OpenKey/Ex if the function fails (py3, py2) return None else: try: value, _ = winreg.QueryValueEx(hkey, query) return value except EnvironmentError: return None finally: winreg.CloseKey(hkey)
def delete_password(self, service, username): """Delete the password for the username of the service. """ try: key_name = self._key_for_service(service) hkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, key_name, 0, winreg.KEY_ALL_ACCESS) winreg.DeleteValue(hkey, username) winreg.CloseKey(hkey) except WindowsError: e = sys.exc_info()[1] raise PasswordDeleteError(e) self._delete_key_if_empty(service)
def _check_long_paths_support(): if platform.system() != "Windows": return True if sys.version_info < (3, 6): return False from six.moves import winreg try: hKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\FileSystem") result = winreg.QueryValueEx(hKey, "LongPathsEnabled") key_value = result[0] return key_value == 1 except EnvironmentError: return False finally: winreg.CloseKey(hKey) return False
def win32InstalledFonts(directory=None, fontext='ttf'): """ Search for fonts in the specified font directory, or use the system directories if none given. A list of TrueType font filenames are returned by default, or AFM fonts if *fontext* == 'afm'. """ from six.moves import winreg if directory is None: directory = win32FontDirectory() fontext = get_fontext_synonyms(fontext) key, items = None, set() for fontdir in MSFontDirectories: try: local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir) except OSError: continue if not local: return list_fonts(directory, fontext) try: for j in range(winreg.QueryInfoKey(local)[1]): try: key, direc, tp = winreg.EnumValue(local, j) if not isinstance(direc, six.string_types): continue # Work around for https://bugs.python.org/issue25778, which # is fixed in Py>=3.6.1. direc = direc.split("\0", 1)[0] if not os.path.dirname(direc): direc = os.path.join(directory, direc) direc = os.path.abspath(direc).lower() if os.path.splitext(direc)[1][1:] in fontext: items.add(direc) except EnvironmentError: continue except WindowsError: continue except MemoryError: continue return list(items) finally: winreg.CloseKey(local) return None
def get_browser_path(): '''获取chorme.exe的路径 ''' from six.moves import winreg sub_key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome" try: hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key) install_dir, _ = winreg.QueryValueEx(hkey, "InstallLocation") winreg.CloseKey(hkey) except WindowsError: try: hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) install_dir, _ = winreg.QueryValueEx(hkey, "InstallLocation") except WindowsError: sub_key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe" hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key) install_dir, _ = winreg.QueryValueEx(hkey, "Path") return install_dir + "\\chrome.exe"
def win32InstalledFonts(directory=None, fontext='ttf'): """ Search for fonts in the specified font directory, or use the system directories if none given. A list of TrueType font filenames are returned by default, or AFM fonts if *fontext* == 'afm'. """ from six.moves import winreg if directory is None: directory = win32FontDirectory() fontext = get_fontext_synonyms(fontext) key, items = None, {} for fontdir in MSFontDirectories: try: local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir) except OSError: continue if not local: return list_fonts(directory, fontext) try: for j in range(winreg.QueryInfoKey(local)[1]): try: key, direc, any = winreg.EnumValue(local, j) if not is_string_like(direc): continue if not os.path.dirname(direc): direc = os.path.join(directory, direc) direc = os.path.abspath(direc).lower() if os.path.splitext(direc)[1][1:] in fontext: items[direc] = 1 except EnvironmentError: continue except WindowsError: continue except MemoryError: continue return list(six.iterkeys(items)) finally: winreg.CloseKey(local) return None
def _get_local_auth(self): username = password = "" if platform.system() in ('Windows', 'Microsoft'): app_data_path = os.environ.get("APPDATA") if not app_data_path: from six.moves import winreg hkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", ) app_data_reg = winreg.QueryValueEx(hkey, "AppData") app_data_path = app_data_reg[0] winreg.CloseKey(hkey) auth_file = os.path.join(app_data_path, "deluge", "auth") else: from xdg.BaseDirectory import save_config_path try: auth_file = os.path.join(save_config_path("deluge"), "auth") except OSError: return username, password if os.path.exists(auth_file): for line in open(auth_file): if line.startswith("#"): # This is a comment line continue line = line.strip() try: lsplit = line.split(":") except Exception: continue if len(lsplit) == 2: username, password = lsplit elif len(lsplit) == 3: username, password, level = lsplit else: continue if username == "localclient": return username, password return "", ""
def _visual_compiler(output, version): 'version have to be 8.0, or 9.0 or... anything .0' if platform.system().startswith("CYGWIN"): return _visual_compiler_cygwin(output, version) if version == "15": vs_path = os.getenv('vs150comntools') path = vs_path or vs_installation_path("15") if path: compiler = "Visual Studio" output.success("Found %s %s" % (compiler, "15")) return compiler, "15" return None version = "%s.0" % version from six.moves import winreg # @UnresolvedImport try: hKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion") winreg.QueryValueEx(hKey, "ProgramFilesDir (x86)") is_64bits = True except EnvironmentError: is_64bits = False finally: winreg.CloseKey(hKey) if is_64bits: key_name = r'SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VC7' else: key_name = r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\SxS\VC7' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_name) winreg.QueryValueEx(key, version) installed_version = Version(version).major(fill=False) compiler = "Visual Studio" output.success("Found %s %s" % (compiler, installed_version)) return compiler, installed_version except EnvironmentError: return None
def get_browser_path(): '''获取chorme.exe的路径 ''' from six.moves import winreg sub_key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome" install_dir = '' try: hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key) install_dir, _ = winreg.QueryValueEx(hkey, "InstallLocation") winreg.CloseKey(hkey) except WindowsError: try: hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) install_dir, _ = winreg.QueryValueEx(hkey, "InstallLocation") except WindowsError: try: sub_key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe" hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key) install_dir, _ = winreg.QueryValueEx(hkey, "Path") except WindowsError: for env_dir in os.getenv('PATH').split(';'): if os.path.exists(os.path.join(env_dir, 'chrome.exe')): install_dir = env_dir break if not install_dir: app_dirs = [ os.getenv('LOCALAPPDATA'), os.getenv('ProgramFiles(x86)'), os.getenv('ProgramW6432') ] for app_dir in app_dirs: if (os.path.exists( os.path.join(app_dir, r'Google\Chrome\Application', 'chrome.exe'))): install_dir = os.path.join( app_dir, r'Google\Chrome\Application') break if not install_dir: raise WindowsError('未找到Chrome可执行文件路径') return os.path.join(install_dir, "chrome.exe")
def get_iscsi_initiator(self): """Get iscsi initiator name for this machine.""" computer_system = self._conn_cimv2.Win32_ComputerSystem()[0] hostname = computer_system.name keypath = ("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\" "iSCSI\\Discovery") try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, keypath, 0, winreg.KEY_ALL_ACCESS) temp = winreg.QueryValueEx(key, 'DefaultInitiatorName') initiator_name = str(temp[0]) winreg.CloseKey(key) except Exception: LOG.info( _LI("The ISCSI initiator name can't be found. " "Choosing the default one")) initiator_name = "iqn.1991-05.com.microsoft:" + hostname.lower() if computer_system.PartofDomain: initiator_name += '.' + computer_system.Domain.lower() return initiator_name
def set_win_env(vars): """ Set Windows environment variable persistently by editing the registry :param vars: ['VAR1=VAL1', 'VAR2=VAL2', 'PATH=SOMEPATH'] """ if is_conda_env(): return set_conda_env(vars) if (not 'win32' in sys.platform): return for newvar in vars: from string import find try: if sys.version_info.major == 2: import six.moves.winreg as winreg else: import winreg except ImportError as e: print("!!ERROR: Can not access to Windows registry.") return def queryValue(qkey, qname): qvalue, type_id = winreg.QueryValueEx(qkey, qname) return qvalue name, value = newvar.split('=') regpath = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) try: key = winreg.OpenKey(reg, regpath, 0, winreg.KEY_ALL_ACCESS) except WindowsError as we: print(("Cannot set "+repr(name)+" for all users. Set for current user.")) winreg.CloseKey(reg) regpath = r'Environment' reg = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) key = winreg.OpenKey(reg, regpath, 0, winreg.KEY_ALL_ACCESS) # Specific treatment for PATH variable if name.upper() == 'PATH': value = os.path.normpath(value) try: actualpath = queryValue(key, name) except: print('No PATH variable found') actualpath = '' listpath = actualpath.split(';') if not (value in listpath): value = actualpath + ';' + value print(("ADD %s to PATH" % (value,))) else: value = actualpath # TEST SIZE if (len(value) >= 8191): print("!!ERROR!! : PATH variable cannot contain more than 8191 characters") print("!!ERROR!! : Please : remove unused value in your environement") value = actualpath if (name and value): expand = winreg.REG_SZ # Expand variable if necessary if ("%" in value): expand = winreg.REG_EXPAND_SZ winreg.SetValueEx(key, name, 0, expand, value) # os.environ[name] = value #not necessary winreg.CloseKey(key) winreg.CloseKey(reg) # Refresh Environment try: HWND_BROADCAST = 0xFFFF WM_SETTINGCHANGE = 0x001A SMTO_ABORTIFHUNG = 0x0002 sParam = "Environment" import win32gui res1, res2 = win32gui.SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, sParam, SMTO_ABORTIFHUNG, 100) if not res1: print(("result %s, %s from SendMessageTimeout" % (bool(res1), res2))) except Exception as e: print(e)