def test_readValues(self): from winreg import OpenKey, EnumValue, QueryValueEx, EnumKey from winreg import REG_SZ, REG_EXPAND_SZ key = OpenKey(self.root_key, self.test_key_name) sub_key = OpenKey(key, "sub_key") index = 0 while 1: try: data = EnumValue(sub_key, index) except EnvironmentError as e: break if data[0] != 'test_name': # cannot wrap a memoryview in setup_class for test_data assert data in self.test_data index = index + 1 assert index == len(self.test_data) + 1 for name, value, type in self.test_data: result = QueryValueEx(sub_key, name) assert result == (value, type) if type == REG_SZ or type == REG_EXPAND_SZ: assert not isinstance(result[0], bytes) assert EnumKey(key, 0) == "sub_key" raises(EnvironmentError, EnumKey, key, 1)
def __win32_finddll(): from winreg import OpenKey, CloseKey, EnumKey, QueryValueEx, \ QueryInfoKey, HKEY_LOCAL_MACHINE from distutils.version import LooseVersion import os dlls = [] # Look up different variants of Ghostscript and take the highest # version for which the DLL is to be found in the filesystem. for key_name in ('AFPL Ghostscript', 'Aladdin Ghostscript', 'GPL Ghostscript', 'GNU Ghostscript'): try: k1 = OpenKey(HKEY_LOCAL_MACHINE, "Software\\%s" % key_name) for num in range(0, QueryInfoKey(k1)[0]): version = EnumKey(k1, num) try: k2 = OpenKey(k1, version) dll_path = QueryValueEx(k2, 'GS_DLL')[0] CloseKey(k2) if os.path.exists(dll_path): dlls.append((LooseVersion(version), dll_path)) except WindowsError: pass CloseKey(k1) except WindowsError: pass if dlls: dlls.sort() return dlls[-1][-1] else: return None
def addFileAssociation(self): """ Associate *.fmu with the FMPy GUI """ try: from winreg import HKEY_CURRENT_USER, KEY_WRITE, REG_SZ, OpenKey, CreateKey, SetValueEx, CloseKey python = sys.executable root, ext = os.path.splitext(python) pythonw = root + 'w' + ext if os.path.isfile(pythonw): target = pythonw else: target = python key_path = r'Software\Classes\fmpy.gui\shell\open\command' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, '"%s" -m fmpy.gui "%%1"' % target) CloseKey(key) key_path = r'SOFTWARE\Classes\.fmu' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, 'fmpy.gui') CloseKey(key) QMessageBox.information(self, "File association added", "The file association for *.fmu has been added") except Exception as e: QMessageBox.critical(self, "File association failed", "The file association for *.fmu could not be added. %s" % e)
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 type(self): """Get resource type. NOTE: this winreg-based method enumerates all resources which makes it a bit slower. But, IT WORKS. >>> import mscluster >>> C = mscluster.Cluster() >>> while (True): ... Cr = next(C.resources) ... if Cr == 'AG-LABC': ... R = C.openResource(Cr) ... Rtype = R.type ... break >>> Rtype 'SQL Server Availability Group' """ with OpenKey(HKEY_LOCAL_MACHINE, "Cluster\Resources") as rsKey: (rskeys, rsvals, rsmod) = QueryInfoKey(rsKey) for n in range(rskeys): rid = EnumKey(rsKey, n) with OpenKey(rsKey, rid) as rKey: (rname, rname_t) = QueryValueEx(rKey, "Name") if rname == self.name: (rtype, rtype_t) = QueryValueEx(rKey, "Type") return rtype raise RuntimeError("Unable to find resource type for [{}]".format( self.name))
def get_info(self, reg): key = OpenKey(HKEY_CURRENT_USER, reg) conns = [] try: i = 0 while 1: name = EnumKey(key, i) conns.append(name) i += 1 except: pass hosts = [] usernames = [] passwords = [] for i in conns: key = OpenKey(HKEY_CURRENT_USER, reg + '\\' + i) try: j = 0 while 1: name, value, type = EnumValue(key, j) if name == 'Host': hosts.append(value) if name == 'UserName': usernames.append(value) if name == 'Pwd': passwords.append(value) j += 1 except: pass CloseKey(key) for i in range(len(hosts)): if len(hosts[i]) is not 0: print 'host_name:' + hosts[i] + ' ' + 'username:'******' ' + 'password:' + passwords[i]
def _users(self): r""" (Windows) This function checks the registry key: ``SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList`` for user sids. If a new account is created, the alert will be triggered after the system is rebooted and is updated to reflect the creation of the account. (Linux) Open the etc/passwd file and extracts all the user's. If a new user is found within this file or if a service account shell has been updated to an interactive logon shell, an alert will be triggered """ target_key = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" allowed_users = tuple(map(lambda s: s.strip(), self.config["users"]["allow"].split("|"))) if self.system == "Windows": with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hklm: with OpenKey(hklm, target_key, 0, KEY_ALL_ACCESS) as profile_list: subkeys = QueryInfoKey(profile_list)[0] for i in range(subkeys): subkey = EnumKey(profile_list, i) if search(r"^S-\d-\d+-(\d+-){1,14}\d+$", subkey): with OpenKey(hklm, f"{target_key}\\{subkey}", 0, KEY_ALL_ACCESS) as user_key: user = QueryValueEx(user_key, r"ProfileImagePath")[0].split("\\")[-1] if user not in allowed_users: message = f"Host: {self.hostname}\nTime: {datetime.now()}\nAlert: c4N4Re has detected a interactive new user: {user}. " \ f"If you have not created a new user or have not changed the shell " \ f"for a service account, then your system might be compromised!" self.__send_alert( self.config["users"]["subject"], message) self.num_of_alerts += 1 else: linux_shells = ( "bash", # GNU Bourne-Again Shell "sh", # Bourne Shell "ksh", # Korn Shell "zsh", # Z Shell "csh" # C Shell ) interactive_users = [] allowed_users = tuple(map(lambda s: s.strip(), self.config["users"]["allow"].split('|'))) with open("/etc/passwd") as passwd: for entry in passwd: entry = entry.strip().split(":") user, shell = entry[0], entry[-1].split('/')[-1] if shell in linux_shells: interactive_users.append(user) for interactive_user in interactive_users: if interactive_user not in allowed_users: message = f"Host: {self.hostname}\nTime: {datetime.now()}\nAlert: c4N4Re has detected " \ f"a new interactive user: {interactive_user}. " \ f"If you have not created a new user or have not changed the shell " \ f"for a service account, then your system might be compromised!" self.__send_alert( self.config["users"]["subject"], message) self.num_of_alerts += 1
def Registrar(Action='get', RegPath='', RegName='', RegValue=''): ClassDict = {'HKEY_CURRENT_USER':HKEY_CURRENT_USER} mainkey = RegPath.split('\\')[0] RegRelativePath = RegPath.replace(mainkey + '\\', '') if Action == 'exists': try: with OpenKey(ClassDict[mainkey], RegRelativePath, 0, KEY_ALL_ACCESS) as key: return(True) except FileNotFoundError: return(False) try: with OpenKey(ClassDict[mainkey], RegRelativePath, 0, KEY_ALL_ACCESS) as key: if Action == 'get': value = QueryValueEx(key, RegName)[0] return(value) elif Action == 'set': SetValueEx(key, RegName, 0, REG_SZ, RegValue) if QueryValueEx(key, RegName)[0]: return(True) else: return(False) elif Action == 'setkey': CreateKey(ClassDict[mainkey], join(RegRelativePath, RegName)) except FileNotFoundError as regerr: pass
def reg_scanner(**kwargs): try: if kwargs.get('source') == 'putty': parent_key = r"SOFTWARE\SimonTatham\PuTTY\Sessions" elif kwargs.get('source') == 'kitty': parent_key = r"SOFTWARE\9bis.com\KiTTY\Sessions" except Exception as error: print( f'Invalid source, please check configuration file or typo... -> {error}' ) parent_reg = ConnectRegistry(None, HKEY_CURRENT_USER) parent_key = OpenKey(parent_reg, parent_key) for sessions in range(int(kwargs.get('sessions'))): try: subkey_name = EnumKey(parent_key, sessions) subkey = OpenKey(parent_key, subkey_name) host = QueryValueEx(subkey, "HostName") port = QueryValueEx(subkey, "PortNumber") username = QueryValueEx(subkey, "UserName") yield (subkey_name, host[0], port[0], username[0]) except OSError as error: #print(error) break
def check_requirements(): extra = 'sudo apt-get -y install clang libglib2.0-dev' if WIN32: extra = f'Visual C++ for Python: {LINK}' if MACOS: extra = f'pkg-config: {LINK}' print(f''' Python support in Lean with pythonnet ===================================== Prerequisites: - Python {VERSION} {ARCH} with pip - LEAN: {README} - {extra} - git It will update {', '.join(PACKAGES)} packages. ''') version = sys.version[0:(5 if LINUX else 3)] arch = "x64" if sys.maxsize > 2**32 else "x86" if version != VERSION or arch != ARCH: conda_in_linux = LINUX and which('conda') is not None print( f'Python {VERSION} {ARCH} is required: version {version} {arch} found.' ) exit(f'Please use "conda install -y python={VERSION}"' if conda_in_linux else '') if which('git') is None: exit( 'Git is required and not found in the path. Link to install: https://git-scm.com/downloads' ) if which('pip') is None: exit('pip is required and not found in the path.') if LINUX: if which('clang') is None: exit(f'clang is required and not found in the path.{extra}') path = '/usr/lib/libpython3.6m.so' if not os.path.exists(path): print('Add symbolic link to python library in /usr/lib') exit(f'sudo ln -s /path/to/miniconda3/lib/libpython3.6m.so {path}') _check_output(['pkg-config', '--libs', 'glib-2.0']) if WIN32: try: from winreg import OpenKey, HKEY_LOCAL_MACHINE tmp = OpenKey(HKEY_LOCAL_MACHINE, '') OpenKey(tmp, r'SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5') except: tmp = 'https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python#windows' exit( f'.NET Frameworks 3.5 not installed.{os.linesep}Please visit {tmp} for details' )
def test_with(self): from winreg import OpenKey with OpenKey(self.root_key, self.test_key_name) as key: with OpenKey(key, "sub_key") as sub_key: assert key.handle != 0 assert sub_key.handle != 0 assert key.handle == 0 assert sub_key.handle == 0
def test_delete(self): from winreg import OpenKey, KEY_ALL_ACCESS, DeleteValue, DeleteKey key = OpenKey(self.root_key, self.test_key_name, 0, KEY_ALL_ACCESS) sub_key = OpenKey(key, "sub_key", 0, KEY_ALL_ACCESS) for name, value, type in self.test_data: DeleteValue(sub_key, name) DeleteKey(key, "sub_key")
def reg_path(path, key_=None): try: if key_ is None: reg_key = OpenKey(HKEY_LOCAL_MACHINE, path, 0, KEY_ALL_ACCESS) else: reg_key = OpenKey(path, key_, 0, KEY_ALL_ACCESS) except: # print(f"registry key {path} is not exist") reg_key = None return reg_key
def test_delete(self): # must be run after test_SetValueEx from winreg import OpenKey, KEY_ALL_ACCESS, DeleteValue, DeleteKey key = OpenKey(self.root_key, self.test_key_name, 0, KEY_ALL_ACCESS) sub_key = OpenKey(key, "sub_key", 0, KEY_ALL_ACCESS) for name, value, type in self.test_data: DeleteValue(sub_key, name) # cannot wrap a memoryview in setup_class for test_data DeleteValue(sub_key, 'test_name') DeleteKey(key, "sub_key")
def is_dir(self, path): localPath = path.replace("/", "\\") rootKey = ConnectRegistry(None, HKEY_CURRENT_USER) try: key = OpenKey(rootKey, localPath) return True except EnvironmentError: pass parent = dirname(path).replace("/", "\\") valueName = basename(path) key = OpenKey(rootKey, parent) value = QueryValueEx(key, valueName) return False
def get_sage_nt_locations_registry(): assert os.name == "nt" sage_key_re = re.compile(r"SageMath-(\d+)\.(\d+)", re.IGNORECASE) with OpenKey(HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall") as root_key: try: for i in count(): subkey_name = EnumKey(root_key, i) m = sage_key_re.search(subkey_name) if m: vmaj, vmin = m.group(1, 2) with OpenKey(root_key, subkey_name) as subkey: location, _ = QueryValueEx(subkey, "InstallLocation") yield Path(location).resolve(), vmaj, vmin except OSError: pass
def getBethesdaGameFolder(gameName): gameFolder = 'Not Detected' gameReg = Info.game_reg(gameName) try: gameFolder = QueryValueEx(OpenKey(ConnectRegistry(None, HKEY_LOCAL_MACHINE), f'SOFTWARE\\Bethesda Softworks\\{gameReg}'),"installed path")[0] except: sm('Did not find game folder in the registry (no WOW6432Node location).', exception=1) if gameFolder == 'Not Detected': try: gameFolder = QueryValueEx(OpenKey(ConnectRegistry(None, HKEY_LOCAL_MACHINE), f'SOFTWARE\\WOW6432Node\\Bethesda Softworks\\{gameReg}'),"installed path")[0] except: sm('Did not find game folder in the registry.', exception=1) return gameFolder
def setup_module(machinery, name, path=None): if machinery.WindowsRegistryFinder.DEBUG_BUILD: root = machinery.WindowsRegistryFinder.REGISTRY_KEY_DEBUG else: root = machinery.WindowsRegistryFinder.REGISTRY_KEY key = root.format(fullname=name, sys_version='%d.%d' % sys.version_info[:2]) base_key = "Software\\Python\\PythonCore\\{}.{}".format( sys.version_info.major, sys.version_info.minor) assert key.casefold().startswith(base_key.casefold()), ( "expected key '{}' to start with '{}'".format(key, base_key)) try: with temp_module(name, "a = 1") as location: try: OpenKey(HKEY_CURRENT_USER, base_key) if machinery.WindowsRegistryFinder.DEBUG_BUILD: delete_key = os.path.dirname(key) else: delete_key = key except OSError: delete_key = base_key subkey = CreateKey(HKEY_CURRENT_USER, key) if path is None: path = location + ".py" SetValue(subkey, "", REG_SZ, path) yield finally: if delete_key: delete_registry_tree(HKEY_CURRENT_USER, delete_key)
def set_keys(self): baseOfficeKeyPath = r"Software\Microsoft\Office" installedVersions = list() try: officeKey = OpenKey(HKEY_CURRENT_USER, baseOfficeKeyPath, 0, KEY_READ) for currentKey in range(0, QueryInfoKey(officeKey)[0]): isVersion = True officeVersion = EnumKey(officeKey, currentKey) if "." in officeVersion: for intCheck in officeVersion.split("."): if not intCheck.isdigit(): isVersion = False break if isVersion: installedVersions.append(officeVersion) CloseKey(officeKey) except WindowsError: # Office isn't installed at all return for oVersion in installedVersions: key = CreateKeyEx( HKEY_CURRENT_USER, r"{0}\{1}\Publisher\Security".format(baseOfficeKeyPath, oVersion), 0, KEY_SET_VALUE) SetValueEx(key, "VBAWarnings", 0, REG_DWORD, 1) SetValueEx(key, "AccessVBOM", 0, REG_DWORD, 1) SetValueEx(key, "ExtensionHardening", 0, REG_DWORD, 0) CloseKey(key)
def _find_devenv_path(vs_version): devenv_path = None # First try the registry, because the environment variable is unreliable # (case of Visual Studio installed on a different drive; it still sets # the envvar to point to C:\Program Files even if devenv.com is on D:\) #pylint: disable=import-error from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE key_path = 'SOFTWARE\\Classes\\VisualStudio.accessor.' + vs_version + '.0\\shell\\Open' try: with OpenKey(HKEY_LOCAL_MACHINE, key_path) as key: cmdline = QueryValue(key, 'Command') if cmdline[:1] == '"': cmdline = cmdline.split('"')[1] elif ' ' in cmdline: cmdline = cmdline.split(' ')[0] devenv_path = cmdline.replace('devenv.exe', 'devenv.com') #pylint: disable=broad-except except Exception: pass # If the registry key is unhelpful, try the environment variable if not devenv_path: vstools_path = os.getenv('VS' + vs_version + '0COMNTOOLS') if vstools_path is not None: # Sanitize this because os.path.join sometimes gets confused if vstools_path[-1] in [ '/', '\\' ]: vstools_path = vstools_path[:-1] devenv_path = os.path.join(vstools_path, '../../Common7/IDE/devenv.com') if not devenv_path or not os.path.exists(devenv_path): return None logging.info("Found Visual Studio at %s", devenv_path) return devenv_path
def verify_registry(): regHandle = ConnectRegistry(None, HKEY_LOCAL_MACHINE) keyHandle = OpenKey(regHandle, r"SOFTWARE\Mozilla\NativeMessagingHosts\org.cryptable.pki.keymgmnt", access=KEY_READ) data = QueryValue(keyHandle, None) print(data) if data != r"C:\Program Files\Cryptable\Key Management Web Extension\org.cryptable.pki.keymgmnt.json": raise "registry verification error"
def PyCharm_go_to(file, line): """ Opens an PyCharm if not opened and moves cursor to specified file and line """ if platform.system() == 'Windows': from winreg import ConnectRegistry, OpenKey, EnumValue, HKEY_CLASSES_ROOT import subprocess reg = ConnectRegistry(None, HKEY_CLASSES_ROOT) raw_key = OpenKey(reg, r"Applications\pycharm.exe\shell\open\command") pycharm_path = "" try: i = 0 while 1: name, pycharm_path, type = EnumValue(raw_key, i) if pycharm_path: break i += 1 except WindowsError: pass pycharm_path = pycharm_path.replace('"%1"', "").strip().strip('"') project_path = Globals.workspace pycharm_process = find_process_by_name("pycharm") if pycharm_process is not None: focus_window_by_pid(pycharm_process.pid) subprocess.Popen([pycharm_path, project_path, "--line", str(line), file])
def __init__(self): super(MainWin,self).__init__() self.setupUi(self) self.Login.triggered.connect(self.open_login) self.RGB.triggered.connect(self.open_image_rgb) self.LoginDialog = LoginDialog() self.ImageMainWin = ImageRGB() # 设置TreeWidgets self.trees = [self.YCPGAMETREE, self.YCPCOMPTREE, self.YLANDFILETREE] for tree in self.trees: tree.setContextMenuPolicy(Qt.CustomContextMenu) tree.customContextMenuRequested.connect(self.show_context_menu) tree.header().setMinimumSectionSize(120) self.model = QFileSystemModel() self.RailID = '' self.ylands_path = '' self.rail_user_data = '' self.ycp_game_folder_path = '' self.ycp_comp_folder_path = '' self.yland_folder_path = '' self.key = OpenKey(HKEY_CURRENT_USER, r"Software\Rail\YlandsRail") _value, type = QueryValueEx(self.key, "InstallPath") if _value: self.ylands_path = _value self.rail_user_data = Path.dirname(self.ylands_path) + '\\' + 'rail_user_data\\2000108' self.YCPTAB.currentChanged.connect(self.refresh_tab_qlistwidget) self.GroupBoxTitleDict = {0: 'YCP游戏目录', 1: 'YCP组件目录', 2: 'YLAND文件目录'} self.YCPTAB.setCurrentIndex(0) print(self.OpenDirBtn.clicked)
def find_bluestacks4_hyperv(serial): """ Find dynamic serial of Bluestacks4 Hyper-v Beta. Args: serial (str): 'bluestacks4-hyperv', 'bluestacks4-hyperv-2' for multi instance, and so on. Returns: str: 127.0.0.1:{port} """ from winreg import ConnectRegistry, OpenKey, QueryInfoKey, EnumValue, CloseKey, HKEY_LOCAL_MACHINE logger.info("Use Bluestacks4 Hyper-v Beta") if serial == "bluestacks4-hyperv": folder_name = "Android" else: folder_name = f"Android_{serial[19:]}" logger.info("Reading Realtime adb port") reg_root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) sub_dir = f"SOFTWARE\\BlueStacks_bgp64_hyperv\\Guests\\{folder_name}\\Config" bs_keys = OpenKey(reg_root, sub_dir) bs_keys_count = QueryInfoKey(bs_keys)[1] for i in range(bs_keys_count): key_name, key_value, key_type = EnumValue(bs_keys, i) if key_name == "BstAdbPort": logger.info(f"New adb port: {key_value}") serial = f"127.0.0.1:{key_value}" break CloseKey(bs_keys) CloseKey(reg_root) return serial
def _find_exe_in_registry(self): try: from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE except ImportError: from winreg import OpenKey, QueryValue, HKEY_LOCAL_MACHINE import shlex keys = ( r"SOFTWARE\Classes\FirefoxHTML\shell\open\command", r"SOFTWARE\Classes\Applications\firefox.exe\shell\open\command" ) command = "" for path in keys: try: key = OpenKey(HKEY_LOCAL_MACHINE, path) command = QueryValue(key, "") break except OSError: pass else: return "" if not command: return "" return shlex.split(command)[0]
def set_setting(s): try: try: DeleteKeyEx(HKEY_LOCAL_MACHINE, AU, KEY_ALL_ACCESS, 0) except FileNotFoundError: pass try: DeleteKeyEx(HKEY_LOCAL_MACHINE, WindowsUpdate, KEY_ALL_ACCESS, 0) except FileNotFoundError: pass CreateKeyEx(HKEY_LOCAL_MACHINE, WindowsUpdate, 0, KEY_ALL_ACCESS) CreateKeyEx(HKEY_LOCAL_MACHINE, AU, 0, KEY_ALL_ACCESS) with OpenKey(HKEY_LOCAL_MACHINE, AU, 0, KEY_ALL_ACCESS) as key: if s == 1: SetValueEx(key, NoAutoUpdate, 0, REG_DWORD, 1) elif s != 0: SetValueEx(key, NoAutoUpdate, 0, REG_DWORD, 0) SetValueEx(key, AUOptions, 0, REG_DWORD, s) SetValueEx(key, ScheduledInstallDay, 0, REG_DWORD, 6) SetValueEx(key, ScheduledInstallTime, 0, REG_DWORD, 3) except PermissionError: print('Permission denied. Please run this program as Administrator.') else: print('Windows Update settings changed successfully.')
def pathExists(hkey, regPath): try: reg = OpenKey(hkey, regPath) except WindowsError: return False CloseKey(reg) return True
def enum_key(hive, subkey: str): with OpenKey(hive, subkey, 0, KEY_ALL_ACCESS) as key: num_of_values = QueryInfoKey(key)[1] for i in range(num_of_values): values = EnumValue(key, i) if values[0] == "LangID": continue print(*values[:-1], sep="\t")
def get_theme() -> str: try: if EnumValue(OpenKey(HKEY_CURRENT_USER, r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\\', 0, KEY_READ), 2)[1]: return 'Light' return 'Dark' except Exception: return 'Dark'
def handle_windows_reg_key(): """ Attempts to add this app to the list of apps that launch at startup checks for value in registry, creates one if it doesn't exist will update key with new location of .exe if it was moved """ from winreg import OpenKey, CloseKey, QueryValueEx, SetValueEx, ConnectRegistry, \ HKEY_CURRENT_USER, REG_SZ, KEY_ALL_ACCESS name = 'wallspotify' path = sys.executable registry = ConnectRegistry(None, HKEY_CURRENT_USER) key = OpenKey(registry, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 0, KEY_ALL_ACCESS) def add(): SetValueEx(key, name, 0, REG_SZ, path) try: data = QueryValueEx(key, name) if data[0] != path: add() except WindowsError: add() CloseKey(key)