Login

Win32 Read Registry Tag

Author:
mpa
Posted:
March 11, 2007
Language:
Python
Version:
Pre .96
Score:
1 (after 1 ratings)

Sometimes you need to grab information from the registry. This will only work if you have admin rights on the box you're querying.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from django import template
import _winreg, os.path

register = template.Library()

# Define the full path to the registry location 
# id = PATH\stringvalue
#
# Only expose a few settings...The alternative is to pass this as a parameter from the template.
str_paths = dict( 
    computername = r'SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\ComputerName',
    spamcount = r'SOFTWARE\Spam\CurrentNumberOfEggs',
    eggcount = r'SOFTWARE\Spam\CurrentNumberOfSpam'
)

@register.filter
def registry( server, reg ):
    '''
    Example usages:
        {% server|registry:"computername" %} to query server's registry setting for str_paths['computername'].
        {% server|registry:"spamcount" %} to query server's registry setting for str_paths['spamcount'].
        {% server|registry:"eggcount" %} to query server's registry setting for str_paths['eggcount'].
    
    '''
    conn, regkey, val = None, None, ('','')
    try:
        regpath, var = os.path.split( str_paths[reg] )
        conn = _winreg.ConnectRegistry(r'\\%s' % server, _winreg.HKEY_LOCAL_MACHINE)
        regkey = _winreg.OpenKey( conn, regpath )
        val = _winreg.QueryValueEx(regkey, var)
    except Exception, e:
        pass
        
    if conn: _winreg.CloseKey( conn )
    if regkey: _winreg.CloseKey( regkey )
    
    return val[0]

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

mpa (on March 11, 2007):

You have to modify the str_paths dictinary to point to meaningful registry paths. The last item on the path should resolve to the REG_SZ key-variable to query.

#

Please login first before commenting.