Scanning through Windows registry...

Lie Lie.1296 at gmail.com
Fri May 16 16:56:10 EDT 2008


On May 17, 2:06 am, Lie <Lie.1... at gmail.com> wrote:
> On May 9, 7:36 pm, Unknown Hero <unknown_hero... at hotmail.com> wrote:> Ah, never mind, got it to work. Here's the code now. I hope I won't
> > run into another problems later :D
>
> > <code snippet>
> > #Goes through all keys and subkeys in the selected hive (defined as
> > root) and replaces the value 'old' with the value 'new'
> > #
> > #IMPORTANT! You should always back up the registry before attempting
> > to modify it.
> > #The author of this script CANNOT BE HELD RESPONSIVE for any damage
> > caused by running this script.
>
> (snip)
>
> One thing though, the disclaimer should not said the author cannot be
> held responsive, or you would be Windows that is not responsive all
> the times. I think it should say "responsible".
>
> I'm quite confused though, the code could be made simpler by dozens
> using Python's high-level functionalities. Particularly the lengthy
> code that checked whether the string contained a substring and replace
> the substring with new could be done easily (and faster) using
> python's in and replace function. I'll post the code later when I
> finished checking places where the codes could be simplified, and I'll
> also polish the entry code and a few other things (and pythonify the
> code according to the PEP 8's guide lines).

The tidied code ++

'''
Goes through all keys and subkeys in the selected hive (defined
as root) and replaces the value 'old' with the value 'new'

IMPORTANT! You should always back up the registry before
attempting to modify it. The author of this script CANNOT BE
HELD RESPONSIBLE for any damage caused by running this script.

You can call the script from a command line and pass two or
three values: HIVE, OLD, and NEW.

OLD and NEW can be any string value
HIVE has to be one of the following:

HKEY_LOCAL_MACHINE / HKLM
HKEY_CURRENT_USER / HKCU
HKEY_CLASSES_ROOT / HKCR
HKEY_USERS / HKU
HKEY_CURRENT_CONFIG / HKCC

If NEW is not specified, values that matches OLD will be replaced
with empty string (i.e. deleted)
'''

import _winreg
import sys

HIVES = {
    "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE,
    "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER,
    "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT,
    "HKEY_USERS" : _winreg.HKEY_USERS,
    "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG,
}

AccessError = False

class RegKey(object):
    def __init__ (self, name, key):
        self.name = name
        self.key = key

    def __str__ (self):
        return self.name

def walk(top):
    """ Walk through each key, subkey, and values

    Walk the registry starting from the key top
    in the form HIVE\\key\\subkey\\..\\subkey and generating
    key, subkey_names, values at each level.

    key is a lightly wrapped registry key, including the name
    and the HKEY object.
    subkey_names are simply names of the subkeys of that key
    values are 3-tuples containing (name, data, data-type).
    See the documentation for _winreg.EnumValue for more details.
    """

    try:
        if "\\" not in top:
            top += "\\"
        root, subkey = top.split ("\\", 1)
        key = _winreg.OpenKey(HIVES[root],
                              subkey,
                              0,
                              _winreg.KEY_READ |
_winreg.KEY_SET_VALUE)

        subkeys = []
        i = 0
        while True:
            try:
                subkeys.append(_winreg.EnumKey(key, i))
                i += 1
            except EnvironmentError:
                break

        values = []
        i = 0
        while True:
            try:
                values.append(_winreg.EnumValue(key, i))
                i += 1
            except EnvironmentError:
                break

        yield RegKey(top, key), subkeys, values

        for subkey in subkeys:
            for result in walk(top + "\\" + subkey):
                yield result

    except WindowsError:
        global AccessError
        AccessError = True



def main(start, startHandle, old, new):
    basickeys = []
    i = 0
    while True:
        try:
            basickeys.append(_winreg.EnumKey(startHandle, i))
            i += 1
        except EnvironmentError:
            break

    for x in basickeys:
        for key, subkey_names, values in walk(start + "\\" + x):
            for (name, data, type) in values:
                if type == _winreg.REG_SZ:
                    if old in data:
                        winreg.SetValueEx(key.key,
                                          name,
                                          0,
                                          type,
                                          data.replace(old, new))
                        print key.key, name, 0, type,
data.replace(old, new)

def help():
    #Show help
    print '''
    USAGE: Registry.py HIVE OLD [NEW]
        HIVE: The root key in registry you want to go through.
            HKEY_CLASSES_ROOT / HKCR
            HKEY_CURRENT_USER / HKCU
            HKEY_LOCAL_MACHINE / HKLM
            HKEY_USERS / HKU
            HKEY_CURRENT_CONFIG / HKCC

        OLD: The value to search for.
            Wrap multiword strings with "".

        NEW: The value which will replace OLD.
            Wrap multiword strings with "".
            If not supplied, it default to empty string
            which means delete all occurence of OLD
            in the registry.

    '''
if __name__ == '__main__':
    if len(sys.argv) < 3 or len(sys.argv) > 4:
        print 'Invalid Number of Arguments'
        help()
        exit()

    ## Root Hive
    try:
        start = {
            'HKCU'                : 'HKEY_CURRENT_USER',
            'HKLM'                : 'HKEY_LOCAL_MACHINE',
            'HKCR'                : 'HKEY_CLASSES_ROOT',
            'HKU'                 : 'HKEY_USERS',
            'HKCC'                : 'HKEY_CURRENT_CONFIG',
        }[sys.argv[1].upper()]
    except KeyError:
        start = sys.argv[1].upper()
    try:

        startHandle = {
            'HKEY_CURRENT_USER'   : _winreg.HKEY_CURRENT_USER,
            'HKEY_LOCAL_MACHINE'  : _winreg.HKEY_LOCAL_MACHINE,
            'HKEY_CLASSES_ROOT'   : _winreg.HKEY_CLASSES_ROOT,
            'HKEY_USERS'          : _winreg.HKEY_USERS,
            'HKEY_CURRENT_CONFIG' : _winreg.HKEY_CURRENT_CONFIG,
        }[start]
    except KeyError:
        print >> sys.stderr, 'Invalid Hive'
        help()
        exit()

    ## The substring to be replaced
    old = sys.argv[2]

    ## The replacement string
    try:
        new = sys.argv[3]
    except:
        new = ''
    main(start, startHandle, old, new)
    if AccessError:
        print '''
Some keys cannot be changed because you don't have the appropriate
permission to modify those keys, please try again with a suitable
user account.
        '''




More information about the Python-list mailing list