Python code to read registry

python 2.7 windows registry
winreg windows 10
python win32api registry
key_all_access
python delete registry key
registry parser
winreg key_read
winreg flushkey
from _winreg import *

"""print r"*** Reading from SOFTWARE\Microsoft\Windows\CurrentVersion\Run ***" """
aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)

aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")
for i in range(1024):
    try:
        asubkey=EnumKey(aKey,i)
        val=QueryValueEx(asubkey, "DisplayName")
        print val
    except EnvironmentError:
        break

Could anyone please correct the error...i just want to display the "DisplayName" within the subkeys of the key the HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall This is the error i get..

Traceback (most recent call last):
  File "C:/Python25/ReadRegistry", line 10, in <module>
    val=QueryValueEx(asubkey, "DisplayName")
TypeError: The object is not a PyHKEY object

Documentation says that EnumKey returns string with key's name. You have to explicitly open it with _winreg.OpenKey function. I've fixed your code snippet:

from _winreg import *

aKey = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)

print r"*** Reading from %s ***" % aKey

aKey = OpenKey(aReg, aKey)
for i in range(1024):
    try:
        asubkey_name=EnumKey(aKey,i)
        asubkey=OpenKey(aKey,asubkey_name)
        val=QueryValueEx(asubkey, "DisplayName")
        print val
    except EnvironmentError:
        break

Please note, that not every key has "DisplayName" value available.

winreg — Windows registry access, These functions expose the Windows registry API to Python. Closes a previously opened registry key. value_name is a string indicating the value to query. settings of environment variables, data about program groups, colors, printers,  The code below shows how to read from/write to the Windows Registry. In this example all the tasks are listed which are executed at logon. A new task (opening the explorer) is added to ths logon.

What about x86 on x64? Use 64-bit Specific Types

What if there's more than 1024 sub-keys in "Uninstall"? Use _winreg.QueryInfoKey(key)

Python 2:

import errno, os, _winreg
proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()

if proc_arch == 'x86' and not proc_arch64:
    arch_keys = {0}
elif proc_arch == 'x86' or proc_arch == 'amd64':
    arch_keys = {_winreg.KEY_WOW64_32KEY, _winreg.KEY_WOW64_64KEY}
else:
    raise Exception("Unhandled arch: %s" % proc_arch)

for arch_key in arch_keys:
    key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", 0, _winreg.KEY_READ | arch_key)
    for i in xrange(0, _winreg.QueryInfoKey(key)[0]):
        skey_name = _winreg.EnumKey(key, i)
        skey = _winreg.OpenKey(key, skey_name)
        try:
            print _winreg.QueryValueEx(skey, 'DisplayName')[0]
        except OSError as e:
            if e.errno == errno.ENOENT:
                # DisplayName doesn't exist in this skey
                pass
        finally:
            skey.Close()

Python 3:

import errno, os, winreg
proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()

if proc_arch == 'x86' and not proc_arch64:
    arch_keys = {0}
elif proc_arch == 'x86' or proc_arch == 'amd64':
    arch_keys = {winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY}
else:
    raise Exception("Unhandled arch: %s" % proc_arch)

for arch_key in arch_keys:
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", 0, winreg.KEY_READ | arch_key)
    for i in range(0, winreg.QueryInfoKey(key)[0]):
        skey_name = winreg.EnumKey(key, i)
        skey = winreg.OpenKey(key, skey_name)
        try:
            print(winreg.QueryValueEx(skey, 'DisplayName')[0])
        except OSError as e:
            if e.errno == errno.ENOENT:
                # DisplayName doesn't exist in this skey
                pass
        finally:
            skey.Close()

Python and reading registry keys. : learnpython, You'll have to open Current Version itself, and parse the value of ProductID out. from winreg import * Registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)  python-registry is a pure Python library that provides read-only access to Windows Registry files. These include NTUSER.DAT, userdiff, and SAM. These include NTUSER.DAT, userdiff, and SAM. The interface is two-fold: a high-level interface suitable for most tasks, and a low-level set of parsing objects and methods which may be used for the advanced study of the Windows Registry.

As it says in the _winreg.QueryValueEx documentation, you need to pass an already open key. EnumKey returns a string, not an open key.

aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)
aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")
for i in range(1024):
    try:
        keyname = EnumKey(aKey, i)
        asubkey = OpenKey(aKey, keyname)
        val = QueryValueEx(asubkey, "DisplayName")
        print val
    except WindowsError:
        break

Python code to read registry, Python code to read registry. from _winreg import * """print r"*** Reading from SOFTWARE\Microsoft\Windows\CurrentVersion\Run ***" """ aReg  Well, the work with the registry is Windows specific and it is rather heavy handed with respect to how it could be implemented in Python. The Windows Registry consists of several trees. Their roots are named with the well known identifiers (like HKEY_CURRENT_USER).

I simplified _winreg functionality for querying a given registry key's nested values.

For instance, this is how straight-forward it is to query the registry key you asked about:

key = r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'

for sub_key in get_sub_keys(key):
    path = join(key, sub_key)
    value = get_values(path, ['DisplayName', 'DisplayVersion', 'InstallDate'])

    if value:
        print value

output

{'DisplayVersion': u'347.25', 'DisplayName': u'NVIDIA Control Panel 347.25', 'InstallDate': u'20150125'}
{'DisplayVersion': u'347.25', 'DisplayName': u'NVIDIA Graphics Driver 347.25', 'InstallDate': u'20150125'}
{'DisplayVersion': u'2.2.2', 'DisplayName': u'NVIDIA GeForce Experience 2.2.2', 'InstallDate': u'20150212'}
...

Add these utility functions as well:

from _winreg import *
import os

roots_hives = {
    "HKEY_CLASSES_ROOT": HKEY_CLASSES_ROOT,
    "HKEY_CURRENT_USER": HKEY_CURRENT_USER,
    "HKEY_LOCAL_MACHINE": HKEY_LOCAL_MACHINE,
    "HKEY_USERS": HKEY_USERS,
    "HKEY_PERFORMANCE_DATA": HKEY_PERFORMANCE_DATA,
    "HKEY_CURRENT_CONFIG": HKEY_CURRENT_CONFIG,
    "HKEY_DYN_DATA": HKEY_DYN_DATA
}

def parse_key(key):
    key = key.upper()
    parts = key.split('\\')
    root_hive_name = parts[0]
    root_hive = roots_hives.get(root_hive_name)
    partial_key = '\\'.join(parts[1:])

    if not root_hive:
        raise Exception('root hive "{}" was not found'.format(root_hive_name))

    return partial_key, root_hive


def get_sub_keys(key):
    partial_key, root_hive = parse_key(key)

    with ConnectRegistry(None, root_hive) as reg:
        with OpenKey(reg, partial_key) as key_object:
            sub_keys_count, values_count, last_modified = QueryInfoKey(key_object)
            try:
                for i in range(sub_keys_count):
                    sub_key_name = EnumKey(key_object, i)
                    yield sub_key_name
            except WindowsError:
                pass


def get_values(key, fields):
    partial_key, root_hive = parse_key(key)

    with ConnectRegistry(None, root_hive) as reg:
        with OpenKey(reg, partial_key) as key_object:
            data = {}
            for field in fields:
                try:
                    value, type = QueryValueEx(key_object, field)
                    data[field] = value
                except WindowsError:
                    pass

            return data


def get_value(key, field):
    values = get_values(key, [field])
    return values.get(field)


def join(path, *paths):
    path = path.strip('/\\')
    paths = map(lambda x: x.strip('/\\'), paths)
    paths = list(paths)
    result = os.path.join(path, *paths)
    result = result.replace('/', '\\')
    return result

williballenthin/python-registry: Pure Python parser for , Contribute to williballenthin/python-registry development by creating an GitHub is home to over 50 million developers working together to host and review code, Python library that provides read-only access to Windows NT Registry files. Fortunately, python-registry provides a set of constants, like Registry.RegSZ, Registry.RegBin, and Registry.RegDWord, to improve readability. When the data is requested from the RegistryValue using the .data () method, it is first converted into the native Python datatype.

Made a simple program to produce a list of the subkeys in the registry. Currently, trying to figure out how to search that list for specific subkeys and then add them if they are not there, and/or change the value. (shouldn't be too difficult) This is what I came up with. I hope it helps, also feel free to critique it:

from winreg import *

registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
def openRegistryA():

    rawKeyA = OpenKey(registry, "SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System")

    try:
        i = 0
        while 1:
            name, value, type = EnumValue(rawKeyA, i)
            print(name, value, i)
            i += 1

    except WindowsError:
        print("END")

    CloseKey(rawKeyA)

def openRegistryB():
    rawKeyB = OpenKey(registry, "SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters")

    try:
        i = 0
        while 1:
            name, value, type = EnumValue(rawKeyB, i)
            print(name, value, i)
            i += 1

    except WindowsError:
        print("END")

    CloseKey(rawKeyB)




openRegistryA()
openRegistryB()

Python code examples on how to read Windows Registry Solutions , I need to write a Python script that will read and display to the screen or a file specified keys of the Windows Registry. How can I do this? Comment  These functions expose the Windows registry API to Python. Instead of using an integer as the registry handle, a handle object is used to ensure that the handles are closed correctly, even if the programmer neglects to explicitly close them. This module offers the following functions: _winreg.CloseKey (hkey) ¶ Closes a previously opened

Tearing up the Windows Registry with python-registry, Python-registry exposes a set of classes in the RegistryParse module that parse and read these low-level structures. One RegistryParse class  OpenKey (key, sub_key, reserved=0, access=KEY_READ) ¶ winreg.OpenKeyEx (key, sub_key, reserved=0, access=KEY_READ) ¶ Opens the specified key, returning a handle object. key is an already open key, or one of the predefined HKEY_* constants. sub_key is a string that identifies the sub_key to open. reserved is a reserved integer, and must be zero. The default is zero.

Python winreg.HKEY_LOCAL_MACHINE() Examples, This page provides Python code examples for winreg. def _get_time_zone_key​(subkey=None): "Return the registry key that stores time zone details" key  Using Python to read data from the registry is very easy. In the following example, we’ll find out where Outlook Express is installed: from _winreg import * key = OpenKey(HKEY_LOCAL_MACHINE, r'Software\Microsoft\Outlook Express', 0, KEY_ALL_ACCESS) QueryValueEx(key, "InstallRoot")

Let's Show #156 - Python Tutorial - Read Registry Key, Python Tutorial: Read Registry Key |||||||||||||||||Links||||||||||||||||| Amazon-Link: http://​amzn.to Duration: 2:45 Posted: May 8, 2015 Reading a Text File in Python. There are actually a number of ways to read a text file in Python, not just one. If you need to extract a string that contains all characters in the file, you can use the following method: file.read() The full code to work with this method will look something like this:

Comments
  • Btw, when you see such error it's worth to try print(type(asubkey).__name__) to get an idea what you're dealing with.
  • You don't have to give the full path for a key if you use an open key as the first parameter when you call OpenKey.
  • It doesn't crash either :-) On my machine the first subkey that EnumKey returns is "AddressBook". It doesn't have "DisplayName" value associated with it, QueryValueEx throws an exception and the loop ends. If you move the query statement into its own try/except block and replace break with pass everything should be fine.
  • and if it doesnt have a DisplayName value available? What then?
  • Misses the last entry, the stop parameter for xrange is exclusive.
  • Thanks, dropped the -1, since I assume that's what you were talking about.
  • Be aware that %PROCESSOR_ARCHITECTURE% returns x86 with 32-bit Python even if the OS is 64-bit.
  • Thank you, this works. But how would I go about extracting values for a specific subkey? If i drill down to a specific program (for the key variable) in the "Uninstall" directory for example, nothing gets returned.