ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/ns_dev/Python/active_prgs2/Source Safe/Printer_Move.py
Revision: 8
Committed: Sat May 5 04:21:19 2012 UTC (13 years, 10 months ago) by ninoborges
Content type: text/x-python
Original Path: Python/NinoCode/active_prgs2/Source Safe/Printer_Move.py
File size: 11185 byte(s)
Log Message:
Initial Import

File Contents

# User Rev Content
1 ninoborges 8 ## Registry.py
2     ## TWGOLDEN 11/02/02
3     ## Updates server name for UNC printers from old value to new
4     from win32api import *
5     from win32con import *
6     import string,os,time,_winreg
7    
8     ## Function: backupKey
9     ## Purpose: backs up a regsitry key and its subkeys to the file specified
10     ## Arguments: regKey - the key you'd like backed up
11     ## backupFileName - the file to back the key up to
12     ## Notes: this function requires that y:\bin\reg.exe exist.
13     def backupPrintersConnectionsKey(backupFileName):
14     result = os.popen( 'y:\\bin\\reg.exe export HKCU\\Printers\\Connections ' + backupFileName )
15     resultText = result.read()
16     if resultText == '\nThe operation completed successfully\n': return 1
17    
18     ## Function: addToLogFile
19     ## Purpose: Writes the string passed in to the designated log file
20     ## Arguments: fileName - name of the log file
21     ## logEntry - string to add to end of log file
22     ## userSpecific - set to 1 if log file stored in the user's netchk dir, 0 if stored globally
23     ## echo - set to 1 to also echo the logEntry string to stdout
24     def addToLogFile(fileName, logEntry, userSpecific=0, echo=0 ):
25     # 1. Check if log file to be global or local to user
26     if userSpecific == 1:
27     # Since user specific, pull user's log directory from the registry
28     # ...
29     hkey = RegOpenKey( HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders' )
30     AppData = RegQueryValueEx( hkey, 'Local AppData' )
31     logDir = AppData[0] + '\\McGuireWoods LLP\\NetChk'
32     else:
33     # Since not user specific, use the global log directory
34     WinDir = GetSystemDirectory()
35     WinDrive = string.split( WinDir, ':' )
36     logDir = WinDrive[0] + ':\\NetChk'
37     logFileName = logDir + '\\' + fileName
38     try:
39     logFile = open( logFileName, 'a' )
40     except IOError:
41     os.makedirs(logDir)
42     logFile = open( logFileName, 'a' )
43     logFile.write( time.strftime('%d/%m/%Y\t%H:%M:%S -\t',time.localtime()) + logEntry + '\n' )
44     if echo == 1: print logEntry
45     logFile.close()
46    
47     ## Function: getBadPrinters
48     ## Purpose: returns a list of printers that match the server string
49     ## Arguments: rootHandle - root registry hive (HKEY_LOCAL_MACHINE, etc.)
50     ## keyName - key whos first level subkeys you wish to search
51     ## findString - string to search for
52     ## Returns: list of matching key names
53     def getBadPrinters(rootHandle, keyName, findString):
54     # open the UNC printer registry key
55     hkey = RegOpenKey( rootHandle, keyName )
56     # get number of printer subkeys
57     numPrinters = RegQueryInfoKey(hkey)
58     printerList=[]
59     # check each printer for the search string
60     for i in range (numPrinters[0]):
61     printerName = RegEnumKey( hkey, i )
62     if string.find(string.lower( printerName ), findString) <> -1:
63     #if string.find(printerName, findString) <> -1:
64     printerList.append(printerName)
65     hkey.Close()
66     return printerList
67    
68     ## Function: fixBadPrinters
69     ## Purpose: fixes the printer key name and server string inside registry
70     ## Arguments: rootHandle - root registry hive (HKEY_LOCAL_MACHINE, etc.)
71     ## keyNameCurrent - key you wish to replace a string in
72     ## stringFind - string to search for
73     ## stringReplace - string to replace the stringFind with
74     ## UPDATE 03.05.03:
75     ## EBorges This function had to be changed a little. This function assumes that all info passed to it is non conditional.
76     ## A condition was added to the end so that it could be iterated over and used to change the registry
77     ## conditionally. This was done to add functionality to also correct printer names.
78     def fixBadPrinters( rootHandle, keyNameCurrent, stringFind, stringReplace ):
79     # 1. Pull key information
80     hkey = RegOpenKey( rootHandle, keyNameCurrent )
81     keyInfo = RegQueryInfoKey( hkey )
82     # 1a. Pull all values/data from key into a list of tuples
83     valueList = []
84     for i in range( keyInfo[1] ):
85     valueList.append(RegEnumValue(hkey,i))
86     # 2. Replace strings in key name and values
87     hkey.Close()
88     keyNameNew = string.replace( string.lower( keyNameCurrent ), stringFind, stringReplace )
89     hkey = RegOpenKey( rootHandle, None )
90     newKey = RegCreateKey( hkey, keyNameNew )
91     # 3. Write new key/values
92     for i in range(len(valueList)):
93     replacer=valueList[i]
94     newValue = [replacer[0],replacer[1]]
95     RegSetValueEx( newKey, newValue[0], 0, REG_SZ, string.replace(string.lower( newValue[1] ), stringFind, stringReplace ) )
96     # 4. Delete old key
97     if keyNameNew != keyNameCurrent.lower():
98     RegDeleteKey( hkey, keyNameCurrent )
99    
100    
101     ## EBorges
102     ## Function: changeWinRegValue
103     ## Purpose: This function will change 1 registry value in place based on a search and replace string.
104     ## This was taken from a class i'm creating that will allow a higher level of registry modifications.
105     ## Because the _winreg methods would interfear with the way the api is being imported in this program,
106     ## this function has been changed to full class calls. i.e _winreg.KEY_WRITE and not just KEY_WRITE.
107     ## Arguments: rootHandle - full class call of one of the HKEY* constants.
108     ## regKey - the key with the value you wish to replace
109     ## valueName - the value name whose information you wish to change
110     ## stringFind - a string to search for in the value's information
111     ## stringReplace - the string it will replace stringFind with
112     def changeWinRegValue(rootHandle,regKey,valueName,stringFind,stringReplace):
113     iKeyObj = _winreg.OpenKey(rootHandle, regKey)
114     result = _winreg.QueryValueEx(iKeyObj,valueName)
115     iKeyObj.Close()
116    
117     value = result[0]
118     type = result[1]
119     value = value.lower()
120     value = value.replace(stringFind,stringReplace)
121     oKeyObj = _winreg.OpenKey(rootHandle, regKey,0,_winreg.KEY_WRITE)
122     _winreg.SetValueEx(oKeyObj,valueName,'',type,value)
123     oKeyObj.Close()
124    
125     ## EBorges
126     ## Function: lookForBadPrinterNames
127     ## Purpose: This function will compare the list of server/printer names that are going to be changed and will
128     ## crossreference this list with a list of bad printer names that need to be changed. This list is held
129     ## in the varible oldNewPrinterGroup. It will not replace this info. It will only return a "to be changed"
130     ## list.
131     ## Arguments: reKeyList - This is the list of registry keys holding the server and printer names.
132     ## printerGroup - This is a list of lists with information for the replace in the following format:
133     ## ((old_string,new_string),(old-string,new_string))
134     ## serverFind - This is the server name that was changed
135     ## serverReplace - This was what it was changed to.
136     ## Returns: newPrinterList - This is a new list of regkeys/printernames that will need to be changed.
137     def lookForBadPrinterNames(regKeyList,printerGroup,serverFind,serverReplace):
138     newPrinterList = []
139     for string in regKeyList:
140     for printerName in printerGroup:
141     string = string.lower()
142     #string = string.replace(printerName[0],printerName[1])
143     string = string.replace(serverFind,serverReplace)
144     #string = string.upper()
145     newPrinterList.append(string)
146     return newPrinterList
147    
148     ## Main
149     if __name__ == '__main__':
150     # Printer name rename Tuple. This tuple folows the following syntax tuple = ((old_printer,new_printer))
151     oldNewPrinterGroup = (('jatrain','ja3076p'),('jac34canon','ja4055mf'),('jacolor-33','ja3064c'),
152     ('jacolor-34','ja4096c'),('ja33canon','ja3074mf'))
153     # set bad server name
154     stringFind = 'jacbdc'
155     # set good server name
156     stringReplace = 'jac'
157     # set log file name
158     logFile = 'Printer_Move_20030305.log'
159     userSpecific = 1
160     # set Registry backup file name
161     WinDir = GetSystemDirectory()
162     WinDrive = string.split( WinDir, ':' )
163     backupDir = WinDrive[0] + ':\\NetChk'
164     regBackupFile = backupDir + '\\Printer_Move_Backup.reg'
165     # Start main section
166     addToLogFile( logFile, 'STARTING Printer_Move.py...', userSpecific, 1 )
167     addToLogFile( logFile, 'Moving any UNC printer mappings on the system from ' + stringFind + ' to ' + stringReplace, userSpecific, 1 )
168     # get list of bad printer paths
169     printersNeedFixin = getBadPrinters( HKEY_CURRENT_USER, 'Printers\\Connections', stringFind )
170     # if bad printer paths exist, back up their settings and fix them
171     if printersNeedFixin:
172     # Now compare this list to the list of bad printer names that need to be changed. If found come back with a second list.
173     printerNamesNeedFixin = lookForBadPrinterNames(printersNeedFixin,oldNewPrinterGroup,stringFind,stringReplace)
174     # Try to back up the reg key. If not sucess exit.
175     if backupPrintersConnectionsKey( regBackupFile ):
176     addToLogFile( logFile, 'Backed up registry settings to file: ' + regBackupFile, userSpecific, 1 )
177     # First replace all the bad server names
178     for i in range( len( printersNeedFixin ) ):
179     addToLogFile( logFile, 'Fixing printer: ' + printersNeedFixin[i], userSpecific, 1 )
180     fixBadPrinters( HKEY_CURRENT_USER, 'Printers\\Connections\\' + printersNeedFixin[i], stringFind, stringReplace )
181     # Now go back to the second list and replace all bad printer names with their good equivalents.
182     for x in range( len( printerNamesNeedFixin ) ):
183     for y in oldNewPrinterGroup:
184     try:
185     fixBadPrinters( HKEY_CURRENT_USER, 'Printers\\Connections\\' + printerNamesNeedFixin[x], y[0],y[1])
186     except:
187     pass
188     # Change the defaults server name to the correct one if it need to be.
189     addToLogFile( logFile, 'Changing the default printer if it is a UNC pointing to '+stringFind + '...',userSpecific, 1)
190     changeWinRegValue( _winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows','Device',stringFind,stringReplace)
191     # Now check to see if the default printer is in the "Change these printer names" group.
192     for p in oldNewPrinterGroup:
193     print "checking for %s" %p[0]
194     changeWinRegValue( _winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows','Device',p[0],p[1])
195     else:
196     addToLogFile( logFile, 'Unable to back up registry key so exiting...', userSpecific, 1 )
197     else:
198     addToLogFile( logFile, 'No printers needed updating so exiting...', userSpecific, 1 )
199     addToLogFile( logFile, 'FINISHED Printer_Move.py', userSpecific, 1 )
200