[melbourne-pug] [Solved] Re: Windows registry PermissionError
Mike Dewhirst
miked at dewhirst.com.au
Fri May 13 04:11:55 EDT 2022
Eryk Sun from python-list at python.org answered my question with some
seriously detailed knowledge.
If you are interested in Windows registry manipulation it would be worth
chasing the thread in their archive.
Here is the finished working (de-identified) code
import winreg as wr
class Registry:
def __init__(self, hkey=None, sub_key=None):
"""
hkey must be one of:
HKEY_LOCAL_MACHINE
HKEY_USERS
HKEY_CURRENT_USER
HKEY_PERFORMANCE_DATA
sub_key is the string location of the registry value
"""
self.computer = None # None means not a remote Registry
self.key = hkey
self.sub_key = sub_key
def connect(self):
# First parameter None means this computer
return wr.ConnectRegistry(None, self.key)
def select(self, access):
""" Returns the open handle for the selected key with guaranteed close() """
with self.connect() as hkey:
return wr.OpenKeyEx(key=hkey, sub_key=self.sub_key, access=access)
def count(self):
"""
Returns a 3-tuple of ints (No. of sub_keys, No. of values, last modified)
"""
access = wr.KEY_QUERY_VALUE
with self.select(access=access) as hkey:
return wr.QueryInfoKey(hkey)
def query(self, vname, access=None):
""" Returns a 2-tuple of (value, registrytype) """
if access is None:
access = wr.KEY_READ | wr.KEY_WOW64_32KEY
with self.select(access=access) as hkey:
return wr.QueryValueEx(hkey, vname)
def setvalue(self, vname, value, access=None):
""" Stores data in the value field of an open registry key."""
if access is None:
access = wr.KEY_SET_VALUE
with self.select(access=access) as hkey:
return wr.SetValueEx(hkey, vname, 0, wr.REG_SZ, value)
if __name__ == "__main__":
""" Read HKLM values and if they exist, write to HKCU. """
sub_key = r"SOFTWARE\XXX Technology\AppName"
# get an open registry handle on the HKLM key/sub_key
lmregistry = Registry(hkey=wr.HKEY_LOCAL_MACHINE, sub_key=sub_key)
# read HKLM reference entries established via the Chemdata install kit
try:
# abandon and quit if not found
anz = lmregistry.query('Country')[0]
db = lmregistry.query('Database')[0]
devref = lmregistry.query('v135')[0]
orgid = lmregistry.query('v136')[0]
except FileNotFoundError:
print("Invalid label. Value not found.")
quit()
# get an open registry handle on the HKCU key/sub_key
curegistry = Registry(hkey=wr.HKEY_CURRENT_USER, sub_key=sub_key)
# write HKCU entries for Chemdata online authentication
try:
# abandon and quit on PermissionError exception
curegistry.setvalue('Country', anz)
curegistry.setvalue('Database', db)
curegistry.setvalue('v135', devref)
curegistry.setvalue('v136', orgid)
except PermissionError as err:
print(f"Permission error. {err}.")
quit()
# display HKCU written entries for testing
print(f"\nHKCU\{curegistry.sub_key}")
# only interested in the first element of each returned tuple
anz = curegistry.query('Country')[0]
print(f"\nCountry = {anz}")
db = curegistry.query('Database')[0]
print(f"\nDatabase version = {db}")
devref = curegistry.query('v135')[0]
print(f"\nDevice Reference = {devref}")
orgid = curegistry.query('v136')[0]
print(f"\nOrganisation ID = {orgid}")
On 13/05/2022 9:24 am, Mike Dewhirst wrote:
> I'm trying to copy a value from HKLM to HKCU for application rollout
> via bulk installation by an administrator but individual Windows user
> authentication. The installer can write to HKLM but the user needs to
> see the value in HKCU
>
> Any hints appreciated.
>
> Thanks
>
> Mike
>
> Getting this ...
>
> Traceback (most recent call last):
> File "D:\Users\mike\envs\chemdata\registry\wreg\wreg.py", line 84,
> in <module>
> curegistry.setvalue('Country', anz)
> File "D:\Users\mike\envs\chemdata\registry\wreg\wreg.py", line 51,
> in setvalue
> return wr.SetValueEx(self.select(), vname, 0, 1, value)
> PermissionError: [WinError 5] Access is denied
>
> from ...
>
> import winreg as wr
>
>
> class Registry:
>
> def __init__(self, computer=None, hkey=None, sub_key=None):
> # computer is None means this computer
> self.computer = computer
> self.key = hkey
> self.sub_key = sub_key
>
> def connect(self):
> return wr.ConnectRegistry(self.computer, self.key)
>
> def select(self):
> # also tried OpenKeyEx()
> return wr.OpenKey(
> key=self.key,
> sub_key=self.sub_key,
> access=wr.KEY_ALL_ACCESS + wr.KEY_WRITE,
> )
>
> def query(self, vname):
> return wr.QueryValueEx(self.select(), vname)
>
> def setvalue(self, vname, value):
> return wr.SetValueEx(self.select(), vname, 0, 1, value)
>
> if __name__ == "__main__":
>
> lmregistry = Registry(
> hkey=wr.HKEY_LOCAL_MACHINE,
> sub_key="SOFTWARE\WOW6432Node\XXX Technology\AppName",
> )
> print(f"\n{lmregistry.sub_key}")
> anz = lmregistry.query('Country')[0]
> print(f"\n{anz}") # works fine
>
> curegistry = Registry(
> hkey=wr.HKEY_CURRENT_USER,
> sub_key="SOFTWARE\XXX Technology\AppName",
> )
> curegistry.setvalue('Country', anz) <<<<< BOOM <<<<<
> anz = curegistry.query('Country')[0]
>
>
>
>
>
>
> --
> Signed email is an absolute defence against phishing. This email has
> been signed with my private key. If you import my public key you can
> automatically decrypt my signature and be sure it came from me. Just
> ask and I'll send it to you. Your email software can handle signing.
--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/melbourne-pug/attachments/20220513/6ed69988/attachment-0001.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: OpenPGP_signature
Type: application/pgp-signature
Size: 495 bytes
Desc: OpenPGP digital signature
URL: <https://mail.python.org/pipermail/melbourne-pug/attachments/20220513/6ed69988/attachment-0001.sig>
More information about the melbourne-pug
mailing list