def set_rdp_keepalive(enable, interval=1): with winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Policies\\Microsoft\\' 'Windows NT\\Terminal Services', 0, winreg.KEY_ALL_ACCESS) as key: LOG.debug("Setting RDP KeepAliveEnabled: %s", enable) winreg.SetValueEx(key, 'KeepAliveEnable', 0, winreg.REG_DWORD, 1 if enable else 0) LOG.debug("Setting RDP keepAliveInterval (minutes): %s", interval) winreg.SetValueEx(key, 'keepAliveInterval', 0, winreg.REG_DWORD, interval)
def _set_registry_ga_params(install_version, install_timestamp): with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\GuestAgent") as key: install_version_str = "%s.%s.%s.%s" % install_version winreg.SetValueEx(key, "Incarnation", 0, winreg.REG_SZ, install_version_str) install_timestamp_str = install_timestamp.strftime( '%m/%d/%Y %I:%M:%S %p') winreg.SetValueEx(key, "VmProvisionedAt", 0, winreg.REG_SZ, install_timestamp_str)
def hide_user(self, username): keypath = ("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" "\\Winlogon\\SpecialAccounts") winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, keypath) keypath = keypath + "\\UserList" with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, keypath) as key: winreg.SetValueEx(key, username, 0, winreg.REG_DWORD, 0)
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 set_config_value(self, name, value, section=None): key_name = self._get_config_key_name(section) with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, key_name) as key: if type(value) == int: regtype = winreg.REG_DWORD else: regtype = winreg.REG_SZ winreg.SetValueEx(key, name, 0, regtype, value)
def remove_values(class_, name, value_substring, options): sep = ';' values = class_.get_values_list(name, sep) new_values = [ value for value in values if value_substring.lower() not in value.lower() ] values = sep.join(new_values) winreg.SetValueEx(class_.key, name, 0, winreg.REG_EXPAND_SZ, values) class_.notify()
def add(class_, name, value, sep=';'): """ Add a value to a delimited variable, but only when the value isn't already present. """ values = class_.get_values_list(name, sep) if value in values: return new_value = sep.join(values + [value]) winreg.SetValueEx(class_.key, name, 0, winreg.REG_EXPAND_SZ, new_value) class_.notify()
def edit(class_, name, value='', options=None): # value, options ignored sep = ';' values = class_.get_values_list(name, sep) e = EditableFile('\n'.join(values)) e.edit() if e.changed: values = sep.join(e.data.strip().split('\n')) winreg.SetValueEx(class_.key, name, 0, winreg.REG_EXPAND_SZ, values) class_.notify()
def set(class_, name, value, options): # consider opening the key read-only except for here # key = winreg.OpenKey(class_.key, None, 0, winreg.KEY_WRITE) # and follow up by closing it. if not value: return class_.delete(name) do_append = options.append or (name.upper() in ('PATH', 'PATHEXT') and not options.replace) if do_append: sep = ';' values = class_.get_values_list(name, sep) + [value] value = sep.join(values) winreg.SetValueEx(class_.key, name, 0, winreg.REG_EXPAND_SZ, value) class_.notify()
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 set_password(self, service, username, password): """Write the password to the registry """ # encrypt the password password_encrypted = _win_crypto.encrypt(password.encode('utf-8')) # encode with base64 password_base64 = base64.encodestring(password_encrypted) # encode again to unicode password_saved = password_base64.decode('ascii') # store the password key_name = self._key_for_service(service) hkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_name) winreg.SetValueEx(hkey, username, 0, winreg.REG_SZ, password_saved)
def _update_registry(): # From MSDN documentation: # # The hook procedure should process a message in less time than the # data entry specified in the LowLevelHooksTimeout value in the # following registry key: # # HKEY_CURRENT_USER\Control Panel\Desktop # # The value is in milliseconds. If the hook procedure times out, the # system passes the message to the next hook. However, on Windows 7 and # later, the hook is silently removed without being called. There is no # way for the application to know whether the hook is removed. def _open_key(rights): return winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Control Panel\Desktop', 0, rights) REG_LLHOOK_KEY_FULL_NAME = r'HKEY_CURRENT_USER\Control Panel\Desktop\LowLevelHooksTimeout' REG_LLHOOK_KEY_VALUE_NAME = 'LowLevelHooksTimeout' REG_LLHOOK_KEY_VALUE_TYPE = winreg.REG_DWORD REG_LLHOOK_KEY_VALUE = 5000 read_key = _open_key(winreg.KEY_READ) try: value, value_type = winreg.QueryValueEx(read_key, REG_LLHOOK_KEY_VALUE_NAME) except WindowsError: value, value_type = (None, None) if value_type != REG_LLHOOK_KEY_VALUE_TYPE or value != REG_LLHOOK_KEY_VALUE: try: write_key = _open_key(winreg.KEY_WRITE) winreg.SetValueEx(write_key, REG_LLHOOK_KEY_VALUE_NAME, 0, REG_LLHOOK_KEY_VALUE_TYPE, REG_LLHOOK_KEY_VALUE) except WindowsError: log.warning( 'could not update registry key: %s, see documentation', REG_LLHOOK_KEY_FULL_NAME) else: log.warning( 'the following registry key has been updated, ' 'you should reboot: %s', REG_LLHOOK_KEY_FULL_NAME)
def _set_registry_vm_type(vm_type="IAAS"): with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows Azure") as key: winreg.SetValueEx(key, "VMType", 0, winreg.REG_SZ, vm_type)
def set_uac_remote_restrictions(self, enable=True): with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, self._SYSTEM_POLICIES_KEY) as key_name: winreg.SetValueEx(key_name, self._LATFP_VALUE_NAME, 0, winreg.REG_DWORD, int(not enable))
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)