IronPython – working with Registry
Here is a code snippet that I wrote recently for IronPython, correcting some registry information that I put by mistake in our image that is used for cloning client PC’s. I’m sure PowerShell script would be even shorter and cleaner, but I had to come with some working code in a hurry.
# -*- coding: cp1250 -*- # odbc_patch.py -- patching my shallowness # AlesK. __about__= "IronPython script // odbc_patch2.py by AlesK" from Microsoft.Win32 import Registry # ----------------------------------------------- # How to enumerate a node from ODBC.INI. # Print System DSN names with SERVER key value if present # (SERVER key is mandatory for MS ODBC for Oracle, MySQL ODBC, # etc., but not for Oracle supplied driver! # # For complete reference to Regirstry class refer to: # msdn.microsoft.com/en-us/library/microsoft.win32.registry.aspx # You can use: # Registry.ClassesRoot|CurrentConfig|CurrentUser| # LocalMachine|PerformanceData|Users # ------------------------------------------------ system_dsn = Registry.LocalMachine.OpenSubKey('Software\\ODBC\\ODBC.INI') for dsn in system_dsn.GetSubKeyNames(): dsn_key = system_dsn.OpenSubKey(dsn) server = dsn_key.GetValue('SERVER') # print only those DSN's that were created with MS ODBC) # and thus have SERVER defined if server is not None: print("DSN=" + dsn + " SERVER=" + str(server)) # ------------------------------------------------------ # How to read and change value in registry. # Registry.GetValue # Registry.SetValue # # The plot: by mistake I added MS at the end of SERVER variable # for DSN's that are using MS ODBC driver. Instead of # SERVER = ORAXMS I really want SERVER = ORAX, striping off MS. # Candidates in my case are: ORAXMS, ORAYMS, ORAZMS. # ------------------------------------------------------ odbc_dsn = ['ORAXMS','ORAYMS','ORAZMS'] odbc_node = "HKEY_LOCAL_MACHINE\\Software\\ODBC\\ODBC.INI" odbc_key = "SERVER" for dsn in odbc_dsn: value = '' value = Registry.GetValue(odbc_node + '\\' + dsn, odbc_key, value) if value in odbc_dsn: Registry.SetValue(odbc_node + '\\' + dsn, odbc_key, dsn.strip('MS')) print("ODBC.INI: patched " + dsn + " SERVER=" + dsn + " to SERVER=" + dsn.strip('MS')) else: print("ODBC.INI: " + dsn + " - nothing to patch.")
Sample output:
C:\Scripts\IronPython\Registry>ipy odbc_patch2.py
DSN=ORAXMS SERVER=ORAXMS
DSN=ORAYMS SERVER=ORAYMS
DSN=ORAZMS SERVER=ORAZMS
DSN=ORA6MS SERVER=ORAT
ODBC.INI: patched ORAXMS SERVER=ORAXMS to SERVER=ORAX
ODBC.INI: patched ORAYMS SERVER=ORAYMS to SERVER=ORAY
ODBC.INI: patched ORAZMS SERVER=ORAZMS to SERVER=ORAZ
Posted on 08.08.2011, in Scripting and tagged python, Scripting. Bookmark the permalink. Comments Off on IronPython – working with Registry.