Scanning through Windows registry...

Unknown Hero unknown_hero007 at hotmail.com
Fri May 9 08:36:59 EDT 2008


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.
#
#To customize the script to your liking, you can alter the values old,
new, root.
#
#old and new can be any string value
#root has to be one of the following:
#
# _winreg.HKEY_LOCAL_MACHINE
# _winreg.HKEY_CURRENT_USER
# _winreg.HKEY_CLASSES_ROOT
# _winreg.HKEY_USERS
# _winreg.HKEY_CURRENT_CONFIG

import _winreg #For accessing windows registry, included in Python
2.0.
import sys #For reading arguments (command line), included in every
Python release.

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
}


class RegKey:

  def __init__ (self, name, key):
     self.name = name
     self.key = key

  def __str__ (self):
    return self.name

def walk (top):
  """walk the registry starting from the key represented by
  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)
#    print "KEY:", root + "\\" + subkey
    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:
#    print 'Could not open key', root + "\\" + subkey + ", access
denied!\n"
    pass

  except:
    print 'Other error!'


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

  for x in range(len(basickeys)):
    for key, subkey_names, values in walk (start + "\\" +
basickeys[x]):
#      print key
      for (name, data, type) in values:
#        print "  ", name, "=>", data
        if type == _winreg.REG_SZ:
          Character = 0
          Correct = 0
          FoundStart = FoundEnd = 0
          Found = False
          for y in range(len(data)):
            try:
              if Character < len(old):
         #       print old[Character], data[y]
                if old[Character] in data[y]:
                  Character = Character + 1
                  Correct = Correct + 1
            except:
              pass
          if Correct is len(old):
#            print 'Debug!'
            Replace = ""
            Character = 0
            for y in range(len(data)):
              if not Found:
                if old[0] in data[y]:
                  FoundStart = int(y)
                  FoundEnd = FoundStart + len(old)
                  Found = True
#            for y in range(FoundStart):
#              Replace = Replace + data[y]

            for y in range(len(new)):
              Replace = Replace + new[y]

#            for y in range(FoundEnd, len(data)):
#              Replace = Replace + data[y]
            Found = True
          if Found:
#            print "OLD:", old, "will be replaced with:", Replace
            _winreg.SetValueEx (key.key, name, 0, type, data.replace
(old, Replace))


def help():
  #Show help
  print 'USAGE: Registry.py [HIVE] [OLD] [NEW]'
  print '  HIVE: The root key in registry you want to go through.'
  print '    HKEY_CLASSES_ROOT'
  print '    HKEY_CURRENT_USER'
  print '    HKEY_LOCAL_MACHINE'
  print '    HKEY_USERS'
  print '    HKEY_CURRENT_CONFIG'
  print ''
  print '  OLD:  The value to search for.'
  print '    Wrap multiword strings with \"\".'
  print ''
  print '  NEW:  The value which will replace OLD.'
  print '    Wrap multiword strings with \"\".'

#Check for arguments
#HIVE, old, new

while True:
  #Check if invalid number of arguments are given
  if len(sys.argv) is 1:
    help()
    break

#  for x in range(len(sys.argv)):
#    print 'sys.argv[' + str(x) + ']:', sys.argv[x]

  #Check if hive is first
  if sys.argv[1].upper() in ('HKEY_CURRENT_USER',
                             'HKEY_LOCAL_MACHINE',
                             'HKEY_CLASSES_ROOT',
                             'HKEY_USERS',
                             'HKEY_CURRENT_CONFIG'):

    start = sys.argv[1].upper()

  else:
    help()
    break

  #Check that not only one argument is given (at least two required,
preferably three)
  if len(sys.argv) is 2:
    help()
    break

  old = sys.argv[2]

  if len(sys.argv) is 4:
    new = sys.argv[3]

  else:
    help()
    break


  if start in ('HKEY_CLASSES_ROOT'):
    startHandle = _winreg.HKEY_CLASSES_ROOT

  elif start in ('HKEY_CURRENT_USER'):
    startHandle = _winreg.HKEY_CURRENT_USER

  elif start in ('HKEY_LOCAL_MACHINE'):
    startHandle = _winreg.HKEY_LOCAL_MACHINE

  elif start in ('HKEY_USERS'):
    startHandle = _winreg.HKEY_USERS

  elif start in ('HKEY_CURRENT_CONFIG'):
    startHandle = _winreg.HKEY_CURRENT_CONFIG

  else:
    help()
    break

  main(start, startHandle, old, new)
  break
</code>



More information about the Python-list mailing list