def get_interfaces(): """Enumerate all registered J2534 04.04 Pass-Thru interface DLLs Returns: dict: A dict mapping display names of any registered J2534 Pass-Thru DLLs to their absolute filepath. The name can be used in user-facing GUI elements to allow selection of a particular Pass-Thru device, and filepath can be passed to :func:`load_interface` to instantiate a :class:`J2534Dll` wrapping the desired DLL. """ if 'win' not in _platform: raise RuntimeError('PyJ2534 currently only supports Windows') else: import winreg ret = {} _64bit = sys.maxsize > 2**32 _passthru_key = (r"Software\\Wow6432Node\\PassThruSupport.04.04\\" if _64bit else r"Software\\PassThruSupport.04.04\\") BaseKey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, _passthru_key) count = winreg.QueryInfoKey(BaseKey)[0] for i in range(count): DeviceKey = winreg.OpenKeyEx(BaseKey, winreg.EnumKey(BaseKey, i)) Name = winreg.QueryValueEx(DeviceKey, "Name")[0] FunctionLibrary = winreg.QueryValueEx(DeviceKey, "FunctionLibrary")[0] ret[Name] = FunctionLibrary return ret
def get_wsl_basepath(self): try: # get default wsl from registory # HKCU\Software\Microsoft\Windows\CurrentVersion\Lxss path = 'Software\\Microsoft\\Windows\\CurrentVersion\\Lxss' self.log(path) key = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, path, access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY) defaultDistribution, regtype = winreg.QueryValueEx( key, 'DefaultDistribution') winreg.CloseKey(key) path = path + '\\' + defaultDistribution self.log(path) key = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, path, access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY) basePath, regtyp = winreg.QueryValueEx(key, 'BasePath') winreg.CloseKey(key) except: basePath = False traceback.print_exc() return basePath
def user2sid(user_name): """ Returns the user id of the provided user name. @param user_id: The user name. """ path = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList" # Opens the specified key path. with reg.OpenKeyEx(reg.HKEY_LOCAL_MACHINE, path) as key: # Iterates through each sub key. for inx in range(reg.QueryInfoKey(key)[0]): key_name = reg.EnumKey(key, inx) # Retrieves information of the provided profile key. with reg.OpenKeyEx(key, key_name) as user_key: # Get the name of the user from its profileImagePath key value. profile_image_path = reg.QueryValueEx(user_key, "ProfileImagePath")[0] user_name_index = profile_image_path.rfind("\\") + 1 # Return the user identification if it matches the provided user name if user_name.lower( ) == profile_image_path[user_name_index:].lower(): return key_name
def list_all_com_ports(vendor_id, product_id, serial_number): ports = [] hkey_path = "SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_{}&PID_{}\\{}"\ .format(vendor_id, product_id, serial_number) try: device_hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, hkey_path) except EnvironmentError as err: return ports try: parent_id = winreg.QueryValueEx(device_hkey, "ParentIdPrefix")[0] except EnvironmentError as err: winreg.CloseKey(device_hkey) return ports winreg.CloseKey(device_hkey) hkey_path = "SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_{}&PID_{}\\{}\\Device Parameters"\ .format(vendor_id, product_id, serial_number) try: device_hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, hkey_path) try: COM_port = winreg.QueryValueEx(device_hkey, "PortName")[0] ports.append(COM_port) except EnvironmentError as err: # No COM port for root device. pass winreg.CloseKey(device_hkey) except EnvironmentError as err: # Root device has no device parameters pass iface_id = 0 while True: hkey_path = "SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_{vid_val}&PID_{pid_val}&"\ "MI_{mi_val}\\{parent_val}&{parent_iface}\\Device Parameters"\ .format(vid_val=vendor_id, pid_val=product_id, mi_val=str(iface_id).zfill(2), parent_val=parent_id, parent_iface=str(iface_id).zfill(4)) iface_id += 1 try: device_hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, hkey_path) except EnvironmentError as err: break try: port_name = winreg.QueryValueEx(device_hkey, "PortName")[0] except EnvironmentError as err: winreg.CloseKey(device_hkey) continue winreg.CloseKey(device_hkey) if com_port_is_open(port_name): ports.append(port_name) return ports
def getFactorioPath(): steamPath = fallbackSteamPath = None # Check for Steam version if sys.platform == 'win32': import winreg try: with winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, r'Software\Valve\Steam') as key: steamPath = Path(winreg.QueryValueEx(key, 'SteamPath')[0]) except FileNotFoundError as err: logger.debug('Registry lookup for Steam installation failed: ', err) elif sys.platform == 'linux': # NOTE: Some people move Steam from the default install location, which the # Steam client seems to support, as it will ask where its files are. # /usr/bin/steam is actually a wrapper script that points Steam in the # right places. I believe that the the wrapper/bootstrap points the # ~/.steam/steam symlink to the proper Steam installation, so we can use it # as a fallback if the default path is invalid. steamPath = Path.home() / '.local' / 'share' / 'Steam' fallbackSteamPath = Path.home() / '.steam' / 'steam' if not steamPath.exists(): logger.warning(f'No Steam installation found at the default path ' f'({steamPath}). Attempting to fall back to ' f"'{fallbackSteamPath}'") steamPath = fallbackSteamPath if fallbackSteamPath.exists( ) else None if steamPath is not None: for library in getSteamLibraries(steamPath): factorioPath = library / 'steamapps' / 'common' / 'Factorio' if factorioPath.exists(): return factorioPath else: logger.debug( 'Could not find Steam installation; attempting to find the ' 'stand-alone installation...') # Check for stand-alone version if sys.platform == 'win32': try: key = winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Uninstall\Factorio_is1' ) factorioPath = winreg.QueryValueEx(key, 'InstallLocation') except FileNotFoundError as err: logger.debug('Registry lookup for Steam installation failed: ', err) elif sys.platform == 'linux': logger.warning('Stand-alone installation lookup is not supported on ' 'Linux, as it is just a simple tarball.') if factorioPath.exists(): return factorioPath else: logger.warning('Could not find a stand-alone installation!') return None
def launch(program=val, filename=filename): if program == "CyberChef": print os.path.getsize(filename) if os.path.getsize(filename) > 12000: tkMessageBox.showwarning(None, message="Data size exceeds 12000 bytes. Sent data will be truncated (due to limit of command line argument length).") cyberchef_input = open(filename, "rb").read(12000) # CyberChef input box automatically replace 0x0d with 0x0a and this breaks data integrity. # So data have to be converted into hex text before sending to CyberChef. # For the detail of the issue, please see https://github.com/gchq/CyberChef/issues/430 . # Data size limit is reduced from 24000 bytes to 12000 bytes due to this conversion. cyberchef_input = binascii.hexlify(cyberchef_input) cyberchef_input = base64.b64encode(cyberchef_input) cyberchef_input = cyberchef_input.replace("+", "%2B") cyberchef_input = cyberchef_input.replace("=", "") cyberchef_url = "file:///%s%s/Desktop/cyberchef.htm#recipe=From_Hex('Auto')&input=%s" % (os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH").replace("\\", "/"), cyberchef_input) # Get path of default browser because "start" built-in command of command prompt drops URL parameters with "file:///" URL scheme reg_key = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice") progid, regtype = winreg.QueryValueEx(reg_key, "ProgId") winreg.CloseKey(reg_key) reg_key = winreg.OpenKeyEx(winreg.HKEY_CLASSES_ROOT, "%s\\shell\\open\\command" % progid) browser_cmd, regtype = winreg.QueryValueEx(reg_key, "") winreg.CloseKey(reg_key) browser_cmd = browser_cmd.replace("%1", cyberchef_url) p = subprocess.Popen(browser_cmd) p.wait() elif program == "Customize menu": # Get path of default text editor try: reg_key = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.txt\\UserChoice") progid, regtype = winreg.QueryValueEx(reg_key, "ProgId") progid = progid.replace("\\", "\\\\") winreg.CloseKey(reg_key) reg_key = winreg.OpenKeyEx(winreg.HKEY_CLASSES_ROOT, "%s\\shell\\open\\command" % progid) editor_cmd, regtype = winreg.QueryValueEx(reg_key, "") winreg.CloseKey(reg_key) editor_cmd = replace_env_in_path(editor_cmd) editor_cmd = editor_cmd.replace("%1", "send_to.json") tkMessageBox.showinfo(None, message="Please edit 'send_to.json' to customize menu.") p = subprocess.Popen(editor_cmd) p.wait() except Exception as e: # Fallback to Notepad tkMessageBox.showinfo(None, message="Please edit 'send_to.json' to customize menu.") p = subprocess.Popen(["C:\\Windows\\notepad.exe", "send_to.json"]) p.wait() else: program = replace_env_in_path(program) if os.path.exists(program): p = subprocess.Popen([program, filename]) p.wait() else: msg = "%s does not exist." % program tkMessageBox.showerror("Error", msg) root.quit()
def findGamePath() -> Union[Path, None]: # Try to find the game path through registry entries and library files from w3modmanager.core.model import verifyGamePath import winreg import vdf try: # try to read Witcher 3 GOG installation path directly # see https://www.gog.com/forum/general/querying_gog_install_path key = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE', access=(winreg.KEY_READ | winreg.KEY_WOW64_64KEY)) subkey = winreg.OpenKeyEx(key, r'WOW6432Node\GOG.com\Games\1207664663') game = winreg.QueryValueEx(subkey, 'exe') game = Path(str(game[0])) if verifyGamePath(game): return game except Exception: # noqa # probably not found pass try: # try to read Steam installation path # see https://stackoverflow.com/questions/34090258/find-steam-games-folder key = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE', access=(winreg.KEY_READ | winreg.KEY_WOW64_64KEY)) subkey = winreg.OpenKeyEx(key, r'WOW6432Node\Valve\Steam') steam = winreg.QueryValueEx(subkey, 'installPath') steam = Path(str(steam[0])) libs = steam.joinpath('steamapps/libraryfolders.vdf') if steam.exists() and libs.is_file(): # found Steam installation, now read library folders manifest # and iterate libraries libdict = vdf.loads(util.readText(libs), mapper=vdf.VDFDict) libvals = libdict['LibraryFolders'] for key in libvals: checkpath = Path(libvals[key]) if checkpath.is_dir() and checkpath.joinpath( 'steamapps').is_dir(): # Steam library path found, now check for Witcher 3 installation steamapps = checkpath.joinpath('steamapps') game = steamapps.joinpath( 'common/The Witcher 3/bin/x64/witcher3.exe') if verifyGamePath(game): return game else: pass except Exception: # noqa # probably not found pass return None
def get_serial_serial_no(vendor_id, product_id, h_dev_info, device_info_data): prop_type = ctypes.c_ulong() required_size = ctypes.c_ulong() instance_id_buffer = ctypes.create_string_buffer(MAX_BUFSIZE) res = setup_api.SetupDiGetDevicePropertyW( h_dev_info, ctypes.byref(device_info_data), ctypes.byref(DEVPKEY.Device.ContainerId), ctypes.byref(prop_type), ctypes.byref(instance_id_buffer), MAX_BUFSIZE, ctypes.byref(required_size), 0) wanted_GUID = GUID(ctypesInternalGUID(instance_id_buffer)) hkey_path = "SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_{}&PID_{}".format( vendor_id, product_id) try: vendor_product_hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, hkey_path) except EnvironmentError as err: return serial_numbers_count = winreg.QueryInfoKey(vendor_product_hkey)[0] for serial_number_idx in range(serial_numbers_count): try: serial_number = winreg.EnumKey(vendor_product_hkey, serial_number_idx) except EnvironmentError as err: continue hkey_path = "SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_{}&PID_{}\\{}"\ .format(vendor_id, product_id, serial_number) try: device_hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, hkey_path) except EnvironmentError as err: continue try: queried_container_id = winreg.QueryValueEx(device_hkey, "ContainerID")[0] except EnvironmentError as err: winreg.CloseKey(device_hkey) continue winreg.CloseKey(device_hkey) if queried_container_id.lower() == str(wanted_GUID).lower(): winreg.CloseKey(vendor_product_hkey) return serial_number winreg.CloseKey(vendor_product_hkey)
def getDevices(): J2534_Device_Reg_Info = [] BaseKey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, PASSTHRU_REG) count = winreg.QueryInfoKey(BaseKey)[0] for i in range(count): DeviceKey = winreg.OpenKeyEx(BaseKey, winreg.EnumKey(BaseKey, i)) Name = winreg.QueryValueEx(DeviceKey, "Name")[0] FunctionLibrary = winreg.QueryValueEx(DeviceKey, "FunctionLibrary")[0] J2534_Device_Reg_Info.append((Name, FunctionLibrary)) return J2534_Device_Reg_Info
def _win10RID(buildNum, isClient): # Special cases: Windows 10 Version 1507, Windows Server long-term servicing channel (LTSC) releases. if isClient and buildNum == 10240: return "Windows 10 1507" elif not isClient and buildNum in server10LTSBuilds: return server10LTSBuilds[buildNum] # Since late 2019 (and confirmed with Server vNext build 20201), # "rs_prerelease" branch designates dev channel build. # Note that in some cases Insider Preview builds may come from what may appear to be # feature update branch such as mn_release for 20H2 Azure release. # If self-host IsRetailOS flag is present (an integer), it is an Insider Preview. # Because NVDA is a 32-bit application, 64-bit view of Registry must be attempted for self-host key. if os.environ.get("PROCESSOR_ARCHITEW6432") in ("AMD64", "ARM64"): selfHostApplicability = winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\WindowsSelfHost\Applicability", access=winreg.KEY_READ | winreg.KEY_WOW64_64KEY ) else: selfHostApplicability = winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\WindowsSelfHost\Applicability" ) try: isRetailOS = winreg.QueryValueEx(selfHostApplicability, "IsRetailOS")[0] except OSError: isRetailOS = 1 winreg.CloseKey(selfHostApplicability) currentVersion = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows NT\CurrentVersion") try: buildBranch = winreg.QueryValueEx(currentVersion, "BuildBranch")[0] except OSError: buildBranch = None if isRetailOS: isRetailOS = buildBranch and not buildBranch.startswith("rs_prerelease") # Version 20H2/2009 and later where a separate display version string is used. # For backward compatibility, release ID variable will store display version string. try: releaseID = winreg.QueryValueEx(currentVersion, "DisplayVersion")[0] except OSError: releaseID = None # Version 1511 and later unless display version string is present. if not releaseID: try: releaseID = winreg.QueryValueEx(currentVersion, "ReleaseID")[0] except OSError: releaseID = "Unknown" winreg.CloseKey(currentVersion) # Insider Preview builds. if not isRetailOS: return "Windows 10 Insider" if isClient else "Windows Server Insider" if isClient: return "Windows 10 {0}".format(releaseID) else: return "Windows Server {0}".format(releaseID)
def write_registry(bank_id, bank_name, bank_path): logger.debug("Writing registry for {} ({}) @ {}".format( bank_name, bank_id, bank_path)) bank_path_parent = str(Path(bank_path).parent) dict_bank = dict(BankName=bank_name.replace(' ', '_'), DRP="000055", DefaultStyleID="gf22245e-19b1-40e1-a37a-699eaa5b4a1d", Key="2ef256c28b85f2f16329acb0a9ba2ea4", Name=bank_name, Path=bank_path_parent, Date="BMRDG7KZR3ZB27DE") dict_version = dict(Major=4, Minor=0, Revision=0) # registry = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) # install config section config_reg_path = r"SOFTWARE\VOCALOID5\Voice\Components\{}".format(bank_id) logger.debug("Writing {}".format(config_reg_path)) try: config_key = winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, config_reg_path, 0, winreg.KEY_WOW64_64KEY | winreg.KEY_ALL_ACCESS) except Exception as ex: config_key = winreg.CreateKeyEx( winreg.HKEY_LOCAL_MACHINE, config_reg_path, 0, winreg.KEY_WOW64_64KEY | winreg.KEY_ALL_ACCESS) # set one key for key, value in dict_bank.items(): logger.debug("Setup key | {} : {}".format(key, value)) winreg.SetValueEx(config_key, key, 0, winreg.REG_SZ, value) winreg.CloseKey(config_key) # install version section version_reg_path = r'SOFTWARE\VOCALOID5\Voice\Components\{}\Version'.format( bank_id) logger.debug("Writing {}".format(version_reg_path)) winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, version_reg_path) try: version_key = winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, version_reg_path, 0, winreg.KEY_WOW64_64KEY | winreg.KEY_ALL_ACCESS) except Exception as ex: version_key = winreg.CreateKeyEx( winreg.HKEY_LOCAL_MACHINE, version_reg_path, 0, winreg.KEY_WOW64_64KEY | winreg.KEY_ALL_ACCESS) for key, value in dict_version.items(): logger.debug("Setup key | {} : {}".format(key, value)) winreg.SetValueEx(version_key, key, 0, winreg.REG_DWORD, value) winreg.CloseKey(version_key) logger.debug("Successfully writing all changes into registry")
def get_device_name(instance_id): """ Get the device name. @param instance_id: Instance id of the device. """ path = "SOFTWARE\\Microsoft\\Windows Portable Devices\\Devices" with reg.OpenKeyEx(reg.HKEY_LOCAL_MACHINE, path) as key: for inx in range(reg.QueryInfoKey(key)[0]): key_name = reg.EnumKey(key, inx) if instance_id in key_name: with reg.OpenKeyEx(key, key_name) as sub_key: return reg.QueryValueEx(sub_key, "FriendlyName")[0]
def getScreenshotFolder(): import winreg reg_steam = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER,"SOFTWARE\\Valve\\Steam") if reg_steam==None: print("你的电脑看起来并没有安装Steam") os.system("pause>nul") sys.exit(0) SteamPath = winreg.QueryValueEx(reg_steam,"SteamPath")[0] reg_users=winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER,"SOFTWARE\\Valve\\Steam\\Users") userlist=[] try: i=0 while True: userlist.append(winreg.EnumKey(reg_users,i)) i+=1 except: pass if len(userlist)==0: print("你的Steam看起来没有登陆过任何账号") print("找不到截图文件夹") os.system("pause>nul") sys.exit(0) elif len(userlist)==1: return SteamPath+"\\userdata\\"+userlist[0]+"\\760\\remote" elif len(userlist)>1: defultAccountName = winreg.QueryValueEx(reg_steam,"LastGameNameUsed")[0] userdic={} for userIndex in range(len(userlist)): cfgPath=SteamPath+"\\userdata\\"+userlist[userIndex]+"\\config\\localconfig.vdf" if os.path.exists(cfgPath): fp=open(cfgPath,"r",encoding="utf8") cfgVdf = vdf.load(fp) fp.close() userdic[userIndex+1]=[cfgVdf["UserLocalConfigStore"]["friends"]["PersonaName"],userlist[userIndex]] del cfgVdf else: userdic[userIndex+1]=[userlist[userIndex],userlist[userIndex]] print("你的Steam登录过不止一个账户,你要把截图同步到哪一个账户里?") defaultIndex=1 for userIndex in range(len(userlist)): if userdic[userIndex+1][0]==defultAccountName: print(str(userIndex+1)+". "+userdic[userIndex+1][0]+"(默认)") defaultIndex=userIndex+1 defultAccountName="" else: print(str(userIndex+1)+". "+userdic[userIndex+1][0]) selectedIndex=input() if selectedIndex.isnumeric()==False or (1>int(selectedIndex) or len(userlist)<=int(selectedIndex)): return SteamPath+"\\userdata\\"+userdic[defaultIndex][1]+"\\760\\remote" else: return SteamPath+"\\userdata\\"+userdic[int(selectedIndex)][1]+"\\760\\remote"
def get_antidote(): antidote_key = r"Software\Druide informatique inc.\Antidote" value = "DossierAntidote" names = ["Antidote.exe", "antido32.exe"] for name in names: latest_sub_key = None try: with winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, antidote_key) as k: try: for n in itertools.count(): sub_key = winreg.EnumKey(k, n) if sub_key[0].isdigit(): latest_sub_key = sub_key except OSError: pass if latest_sub_key: sub_key = r"{}\{}\Installation".format( antidote_key, latest_sub_key) with winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, sub_key) as k: directory = winreg.QueryValueEx(k, value)[0] path = os.path.join(directory, name) if os.path.isfile(path): return path except FileNotFoundError: pass try: return get_path_from_registry(winreg.HKEY_LOCAL_MACHINE, antidote_key, value, name) except FileNotFoundError: pass for env in ["PROGRAMFILES", "PROGRAMW6432"]: try: program_files = os.environ[env] except KeyError: continue for antidote_dir in [ r"Druide\Antidote*\Programmes*", r"Druide\Antidote*" ]: path = os.path.join(program_files, antidote_dir, name) paths = glob.glob(path) if paths: return sorted(paths)[-1] raise FileNotFoundError("can't find Antidote")
def _win10RID(buildNum, isClient): # Special cases: Windows 10 Version 1507, Windows Server long-term servicing channel (LTSC) releases. if isClient and buildNum == 10240: return "Windows 10 1507" elif not isClient and buildNum in server10LTSBuilds: return server10LTSBuilds[buildNum] # For others, both CurrentVersion and WindowsSelfHost must be consulted. # The former is the case for ReleaseID (DisplayVersion in 20H2/2009 and later) and the latter for Insider Preview detection. # When it comes to the actual order, check self-host flag first. # Because NVDA is a 32-bit application, 64-bit view of Registry must be attempted for self-host key. # If IsRetailOS is present (an integer), it is an Insider Preview. if os.environ.get("PROCESSOR_ARCHITEW6432") in ("AMD64", "ARM64"): selfHostApplicability = winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\WindowsSelfHost\Applicability", access=winreg.KEY_READ | winreg.KEY_WOW64_64KEY) else: selfHostApplicability = winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\WindowsSelfHost\Applicability") try: isRetailOS = winreg.QueryValueEx(selfHostApplicability, "IsRetailOS")[0] except OSError: isRetailOS = 1 winreg.CloseKey(selfHostApplicability) # Insider Preview builds. if not isRetailOS: return "Windows 10 Insider" if isClient else "Windows Server Insider" currentVersion = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows NT\CurrentVersion") # Version 20H2/2009 and later where a separate display version string is used. # For backward compatibility, release ID variable will store display version string. try: releaseID = winreg.QueryValueEx(currentVersion, "DisplayVersion")[0] except OSError: releaseID = None # Version 1511 and later unless display version string is present. if not releaseID: try: releaseID = winreg.QueryValueEx(currentVersion, "ReleaseID")[0] except OSError: releaseID = "Unknown" winreg.CloseKey(currentVersion) if isClient: return "Windows 10 {0}".format(releaseID) else: return "Windows Server {0}".format(releaseID)
def remove_dir_from_win_path(self, remove_dir): import winreg try: env = None path = None env = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, 'Environment', 0, winreg.KEY_SET_VALUE | winreg.KEY_READ) path = winreg.QueryValueEx(env, 'Path')[0] path_lower = path.lower() remove_dir = remove_dir.replace('/', '\\') remove_dir_lower = remove_dir.lower() start_pos = path_lower.find(remove_dir_lower) if (start_pos >= 0): length = len(remove_dir_lower) need_remove = path[start_pos:(start_pos + length)] path = path.replace(need_remove, '') path = path.replace(';;', ';') winreg.SetValueEx(env, 'Path', 0, winreg.REG_SZ, path) winreg.FlushKey(env) winreg.CloseKey(env) print(' ->Remove directory \"%s\" from PATH!\n' % remove_dir) except Exception: print(' ->Remove directory \"%s\" from PATH failed!\n' % remove_dir)
def _get_home_dir(version): """ Return the LightTools home directory. Get the home directory of the specified LightTools `version` from the Windows registry. The requested LightTools `version` must be installed on the system. Args: version (str): The LightTools `version` string, e.g. "8.5.0". Returns: str: The LightTools home directory. """ try: hkey = winreg.OpenKeyEx( key=winreg.HKEY_LOCAL_MACHINE, sub_key=( "SOFTWARE\\Optical Research Associates\\LightTools" "\\{}\\Environment" ).format(version), ) except OSError: msg = ( "Couldn't find home directory of LighTools version {!r}. Please " "check if the requested version of LightTools is installed." ) raise ValueError(msg.format(version)) else: value, __ = winreg.QueryValueEx(hkey, "LT_HOME") return value
def set_environ(self, server=None, port=None): """ str server, int port """ if not self.__setFirst: self.prev_http_proxy, self.prev_https_proxy = os.environ.get( 'HTTP_PROXY'), os.environ.get('HTTPS_PROXY') self.__setFirst = True self.unset_environ() #いったん設定情報を削除 if server != None and port != None: os.environ["HTTP_PROXY"] = "%s:%i" % (server, port) os.environ["HTTPS_PROXY"] = "%s:%i" % (server, port) return try: pac = get_pac() path = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings" key = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, path) p, regtype = winreg.QueryValueEx(key, "ProxyServer") e, regtype = winreg.QueryValueEx(key, "ProxyEnable") except (WindowsError, UnicodeDecodeError): return finally: try: winreg.CloseKey(key) except: pass if bool(e): os.environ["HTTP_PROXY"] = p os.environ["HTTPS_PROXY"] = p elif pac: resolver = ProxyResolver(pac, proxy_auth=self.proxy_auth) proxies = resolver.get_proxy_for_requests(self.url) # Cannot set None for environ. (#27) os.environ['HTTP_PROXY'] = proxies.get('http') or '' os.environ['HTTPS_PROXY'] = proxies.get('https') or ''
def _reg_read_key_table(key, num_sub_keys) -> "KeyTable": key_table = {} for i in range(num_sub_keys): child_key_name = winreg.EnumKey(key, i) with winreg.OpenKeyEx(key, child_key_name) as child_key: key_table[child_key_name] = _reg_read_table(child_key) return key_table
def get_python_installations(): """Returns a list of python executables on the machine.""" installations = set() search_keys = [ (winreg.HKEY_CURRENT_USER, r"Software\Python", 0), (winreg.HKEY_LOCAL_MACHINE, r"Software\Python", winreg.KEY_WOW64_64KEY), (winreg.HKEY_LOCAL_MACHINE, r"Software\Python", winreg.KEY_WOW64_32KEY), ] for hive, key, flags in search_keys: try: with winreg.OpenKeyEx(hive, key, access=winreg.KEY_READ | flags) as root_key: for company in _enum_keys(root_key): with winreg.OpenKey(root_key, company) as company_key: for tag in _enum_keys(company_key): with winreg.OpenKey(company_key, tag) as tag_key: installations.add( _create_python_installation( company, tag, tag_key)) except FileNotFoundError: continue return installations
def process_company(hive_name, company, root_key, default_arch): with winreg.OpenKeyEx(root_key, company) as company_key: for tag in enum_keys(company_key): spec = process_tag(hive_name, company, company_key, tag, default_arch) if spec is not None: yield spec
def _find_vc2015(): try: key = winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\VisualStudio\SxS\VC7", access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY ) except OSError: log.debug("Visual C++ is not registered") return None, None best_version = 0 best_dir = None with key: for i in count(): try: v, vc_dir, vt = winreg.EnumValue(key, i) except OSError: break if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir): try: version = int(float(v)) except (ValueError, TypeError): continue if version >= 14 and version > best_version: best_version, best_dir = version, vc_dir return best_version, best_dir
def set(self, value): opened_key = winreg.OpenKeyEx(self.root, self.path, access=winreg.KEY_WRITE) winreg.SetValueEx(opened_key, self.key_name, 0, winreg.REG_DWORD, value) winreg.CloseKey(opened_key)
def win_ver(): """ Get Windows version info """ csd = sys.getwindowsversion()[-1] # Use the registry to get product name, e.g. 'Windows 7 Ultimate'. # Not recommended, but we don't care. pname = "Windows" release = "" build = "" key = None sam = winreg.KEY_READ if platform.machine() == "AMD64": sam |= winreg.KEY_WOW64_64KEY try: key = winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion", 0, sam) pname = winreg.QueryValueEx(key, "ProductName")[0] build = "Build %s" % winreg.QueryValueEx(key, "CurrentBuildNumber")[0] # Since Windows 10 release = "Version %s" % winreg.QueryValueEx(key, "ReleaseId")[0] build += ".%s" % winreg.QueryValueEx(key, "UBR")[0] except Exception as e: pass finally: if key: winreg.CloseKey(key) return pname, csd, release, build
def query(self): opened_key = winreg.OpenKeyEx(self.root, self.path, access=winreg.KEY_READ) values = winreg.QueryValueEx(opened_key, self.key_name) winreg.CloseKey(opened_key) return values
def check_odbc_entry_windows(server_name, reset=False, arch_keys = {'KEY_WOW64_32KEY', 'KEY_WOW64_64KEY'}): """checks whether the server is registered in the system, and if not launches ODBC management program""" arch_keys = [getattr(winreg, kk) for kk in arch_keys] if not reset: for arch_key in arch_keys: try: key = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, r"Software\ODBC\ODBC.INI", 0, winreg.KEY_READ | arch_key) #skey = winreg.OpenKey(key, skey_name) n_subkeys, n_entries, _ = winreg.QueryInfoKey(key) for n in range(n_subkeys): subkey = winreg.OpenKey(key, winreg.EnumKey(key, n)) n_subsubkeys, n_subentries, _ = winreg.QueryInfoKey(subkey) keydict = (_get_leafs(subkey, n_subentries)) logging.debug("winreg entry: " + str(keydict)) if "Server" in keydict and (keydict["Server"]==server_name): logging.debug("found a 'Server' entry: " + keydict["Server"]) return None # value = winreg.QueryValue(key, skey_name) except (FileNotFoundError, WindowsError): pass os.system('c:\\Windows\\SysWOW64\\odbcad32.exe') return None
def get_config_info_from_registry(key_name: str) -> str: hive, key, flags = (winreg.HKEY_LOCAL_MACHINE, r'Software\Natlink', winreg.KEY_WOW64_32KEY) with winreg.OpenKeyEx(hive, key, access=winreg.KEY_READ | flags) as natlink_key: result, _ = winreg.QueryValueEx(natlink_key, key_name) return result
def _find_vcvarsall(): with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\VisualStudio\SxS\VC7", access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY) as key: if not key: log.debug("Visual C++ is not registered") return None best_version = 0 best_dir = None for i in count(): try: v, vc_dir, vt = winreg.EnumValue(key, i) except OSError: break if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir): try: version = int(float(v)) except (ValueError, TypeError): continue if version >= 14 and version > best_version: best_version, best_dir = version, vc_dir if not best_version: log.debug("No suitable Visual C++ version found") return None vcvarsall = os.path.join(best_dir, "vcvarsall.bat") if not os.path.isfile(vcvarsall): log.debug("%s cannot be found", vcvarsall) return None return vcvarsall
def get_apps_sid(): sid_list = [] with wr.OpenKeyEx(wr.HKEY_CURRENT_USER, BASE_PATH) as key: max_index = wr.QueryInfoKey(key)[0] for i in range(max_index): sid_list.append(wr.EnumKey(key, i)) return sid_list
def _save(self): """ Save '_paths' System Path value into registry. Params: None Returns: None Raises: EnvironmentError if the user is not an "admin" or the admin check fails WindowsError if an error occurred when try to edit System Path value """ # Admin check is_admin = False try: is_admin = ctypes.windll.shell32.IsUserAnAdmin() except Exception: raise EnvironmentError( 'Windows OS detected, but admin check failed') if not is_admin: raise EnvironmentError( 'Edit System Path value requires "Admin" privileges') # Write on System Path value = os.pathsep.join(self._paths) + os.pathsep with winreg.OpenKeyEx(self._root_key, self._sub_key, 0, winreg.KEY_WRITE) as key: winreg.SetValueEx(key, self._value_name, 0, winreg.REG_EXPAND_SZ, value) winreg.FlushKey(key)