A script to automate the movement of databases from one Microsoft SQL Server to another. Designed to detach, copy, and reattach database files with a single call. Used to move databases with a minimum of downtime.
Process contains examples of Windows Cluster detection, and the querying of physical database characteristics and operations (default directories, list of files comprising database, detach/attach, login/SID matching).
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | # dbmove.py - M.Keranen (mksql@yahoo.com) [11/24/03]
# ----------------------------------------------------------------------------------------
# Automate the process of moving databases from one SQL Server to another.
# Assumes current login has administrator access to $ shares on source and target servers.
# ----------------------------------------------------------------------------------------
# Usage: python dbmove.py source_server, sa_password, target_server, sa_password, dbname, db_target_path, log_target_path, connect_string_path
import os, string, sys, time, win32file, win32com.client, win32net
from _winreg import *
def clusterdetect(server):
# Detect the presence of a clustered virtual instance, and return the proper
# SQL Server network name of the server
try: rReg = ConnectRegistry(target,HKEY_LOCAL_MACHINE)
except:
print "Unable to connect to registry on server %s" % (server)
sys.exit()
else:
key = "SOFTWARE\\Microsoft\\Microsoft SQL Server\\" + server + "\\Cluster"
try: rKey = OpenKey(rReg, key)
except: clustername = server
else:
try: clustername = QueryValueEx(rKey,"ClusterName")[0]
except:
clustername = string.lower(server)
print "* No ClusterName key defined in registry on server %s" % (server)
else:
clustername = string.lower("%s\\%s" % (server,clustername))
print "Cluster detected: %s" % (clustername)
CloseKey(rKey)
CloseKey(rReg)
return clustername
def getdefaultdirs(server):
# Retrieve default database and log directories from target server
try: rReg = ConnectRegistry(target,HKEY_LOCAL_MACHINE)
except:
print "Unable to connect to registry on server %s" % (server)
sys.exit()
else:
try: rKey = OpenKey(rReg, r"SOFTWARE\Microsoft\MSSQLServer\MSSQLServer")
except:
print "Unable to open registry key on server %s" % (server)
sys.exit()
else:
dbdir = [None,None]
try: dbdir[0] = QueryValueEx(rKey,"DefaultData")[0]
except: print " * No DefaultData key defined in target registry"
try: dbdir[1] = QueryValueEx(rKey,"DefaultLog")[0]
except: print " * No Defaultlog key defined in target registry"
CloseKey(rKey)
CloseKey(rReg)
return dbdir
def getdbfileinfo(server, sap, dbname):
#Query server for source files. Returns a list of all files belonging to the database.
adoConn = win32com.client.Dispatch('ADODB.Connection')
connect = "Provider=SQLOLEDB.1;Data Source=%s;Initial Catalog=%s;User ID=sa;Password=%s" % (server, dbname, sap)
try: adoConn.Open(connect)
except:
print " ! getdbfileinfo: Unable to connect to %s.%s" % (source,dbname)
return False
sql = "SELECT filename FROM sysfiles ORDER BY fileid"
try: rs = adoConn.Execute(sql)
except:
print " ! getdbfileinfo: Unable to query file info for %s.%s" % (source,dbname)
print " ->%s" % (sql)
return False
srcfiles=[]
while not rs[0].EOF:
srcfiles.append(string.strip(rs[0].Fields(0).Value))
rs[0].MoveNext()
rs[0].Close()
adoConn.Close()
adoConn = None
return srcfiles
def detachdb(server, sap, dbname):
print " DETACH: %s.%s" % (server,dbname)
adoConn = win32com.client.Dispatch('ADODB.Connection')
connect = "Provider=SQLOLEDB.1;Data Source=%s;Initial Catalog=master;User ID=sa;Password=%s" % (server, sap)
try: adoConn.Open(connect)
except:
print " ! detachdb: Unable to connect to %s.%s" % (server,dbname)
return False
#sql = "EXEC sp_dboption '%s', 'trunc. log on chkpt.', 'TRUE'" % (dbname)
#try: adoConn.Execute(sql)
#except:
# print " ! detachdb: Unable to set truncate dboption for %s.%s" % (server,dbname)
# print " ->%s" % (sql)
# return False
# Wait for user connections to clear from database
sql = "select sysprocesses.hostname from sysprocesses,sysdatabases where sysprocesses.dbid = sysdatabases.dbid and name = '%s'" % (dbname)
try: rs = adoConn.Execute(sql)
except:
print " ! detachdb: Unable to query sysprocesses on %s" % (server)
print " ->%s" % (sql)
return False
if not rs[0].EOF:
print(" Database in use on " + (string.strip(rs[0].Fields(0).Value))),
while not rs[0].EOF:
rs = adoConn.Execute(sql)
print("."),
time.sleep(5)
print " "
sql = "CHECKPOINT"
try: adoConn.Execute(sql)
except:
print " ! detachdb: Unable to checkpoint %s.%s" % (server,dbname)
print " ->%s" % (sql)
return False
sql = "EXEC sp_detach_db @dbname = %s" % (dbname)
try: adoConn.Execute(sql)
except:
print " ! detachdb: Unable to execute detach for %s.%s" % (server,dbname)
print " ->%s" % (sql)
return False
adoConn.Close()
adoConn = None
return True
def copydb(source,srcpath,target,tgtpath):
print " COPY: (%s)%s -> (%s)%s" % (source,srcpath,target,tgtpath)
srcfile = '\\\\'+source+'\\'+srcpath[0]+"$"+srcpath[2:]
tgtfile = '\\\\'+target+'\\'+tgtpath[0]+"$"+tgtpath[2:]+'\\'+srcpath[srcpath.rfind('\\')+1:]
try: win32file.CopyFile(srcfile,tgtfile,0)
except:
print " ! Unable to copy %s -> %s" % (srcfile,tgtfile)
return False
return True
def attachsinglefiledb(server, sap, dbname, mdfile):
# Single file attach
print " ATTACH SINGLE: %s.%s" % (server,dbname)
adoConn = win32com.client.Dispatch('ADODB.Connection')
connect = "Provider=SQLOLEDB.1;Data Source=%s;Initial Catalog=master;User ID=sa;Password=%s" % (server, sap)
try: adoConn.Open(connect)
except:
print " ! attachsinglefiledb: Unable to connect to %s" % (server)
return False
sql = "EXEC sp_attach_single_file_db @dbname = '%s', @physname = '%s'" % (dbname,mdfile)
try: adoConn.Execute(sql)
except:
print " ! attachsinglefiledb: Unable to execute attach for %s.%s" % (server,dbname)
print " ->%s" % (sql)
return False
adoConn.Close()
adoConn = None
return True
def attachdb(server, sap, dbname, mdfile, ldfile):
# Data and Log file attach
print " ATTACH: %s.%s" % (server,dbname)
adoConn = win32com.client.Dispatch('ADODB.Connection')
connect = "Provider=SQLOLEDB.1;Data Source=%s;Initial Catalog=master;User ID=sa;Password=%s" % (server, sap)
try: adoConn.Open(connect)
except:
print " ! attachdb: Unable to connect to %s" % (server)
return False
sql = "EXEC sp_attach_db @dbname = '%s', @filename1 = '%s', @filename2 = '%s'" % (dbname,mdfile,ldfile)
try: adoConn.Execute(sql)
except:
print " ! attachdb: Unable to execute attach for %s.%s" % (server,dbname)
print " ->%s" % (sql)
return False
adoConn.Close()
adoConn = None
return True
def loginfix(server,sap,dbname,username):
adoConn = win32com.client.Dispatch('ADODB.Connection')
connect = "Provider=SQLOLEDB.1;Data Source=%s;Initial Catalog=%s;User ID=sa;Password=%s" % (server, dbname, sap)
try: adoConn.Open(connect)
except:
print " ! loginfix: Unable to connect to %s.%s" % (server,dbname)
return False
sql = 'exec sp_change_users_login "UPDATE_ONE","%s","%s"' % (username,username)
try: adoConn.Execute(sql)
except:
print " ! loginfix: Unable to execute sp_login_fix for %s.%s" % (server,dbname)
print " ->%s" % (sql)
return False
adoConn.Close()
adoConn = None
return True
def fgrepcs(oldsrv, olddb, newsrv, connectpath):
# Create a new verions of the file, search each input file line the file for server & db names,
# replace them, and write to a new file.
for file in connectpath:
print " CONNECTION STRING: %s" % (file)
try: fp = open(file, 'r')
except:
print " ! Unable to open connection string file"
return False
try: fpr = open(file+'.new','w')
except:
print" ! Unable to create new connection string file"
return False
for line in fp.readlines():
line = line.lower()
line = line.replace(oldsrv.lower(),newsrv.lower())
fpr.writelines(line)
fpr.close()
fp.close()
oldfile = file+'.old'
i=0
while os.path.exists(oldfile):
i=i+1
oldfile = file + ('.old%s') % i
try: win32file.MoveFile(file,oldfile)
except:
print " ! Unable to rename old file"
return False
try: win32file.MoveFile(file+'.new',file)
except:
print " ! Unable to rename new file"
return False
return True
if __name__ == '__main__':
print ""
if len(sys.argv)>1: param = sys.argv[1].split(',')
if len(sys.argv)<2 or len(param)<7:
print "\Usage: source_server, sa_password, target_server, [sa_password], dbname,"
print " [db_target_path], [log_target_path] | [*], [connect_file_path] | [*]\n"
print " log_target_path = * : Do not copy transaction log file (SQL recreates)"
print " connect_file_path = * : Do not update connection string file"
sys.exit()
source=string.lower(param[0])
srcsa=string.lower(param[1])
target=string.lower(param[2])
tgtsa=string.lower(param[3])
if tgtsa == '': tgtsa = srcsa
dbname=string.lower(param[4])
tgtpath1=string.lower(param[5])
tgtpath2=string.lower(param[6])
connectpath=string.lower(param[7])
#If no connection string path is supplied, collect file paths from connect file catalog
if connectpath == '':
connectpath = []
for line in open('connects.txt','r').readlines():
line = string.lower(line)
conninfo = string.split(string.strip(line),',')
if conninfo[1]==source and conninfo[2]==dbname: connectpath.append(conninfo[3])
sourcesql = clusterdetect(source)
targetsql = clusterdetect(target)
if (tgtpath1=='') or (tgtpath2==''):
dbdirs = getdefaultdirs(target)
if tgtpath1=='': tgtpath1 = dbdirs[0]
if tgtpath2=='': tgtpath2 = dbdirs[1]
if tgtpath1[-1]=='\\': tgtpath1=tgtpath1[:-1]
if tgtpath2[-1]=='\\': tgtpath2=tgtpath2[:-1]
print "\n%s.%s" % (source,dbname)
failsafe = False
srcfiles=getdbfileinfo(source,srcsa,dbname)
if srcfiles:
if detachdb(sourcesql,srcsa,dbname):
failsafe = True
if tgtpath2 == '*':
if copydb(source,srcfiles[0],target,tgtpath1):
tgtpath1=tgtpath1+'\\'+string.split(string.strip(srcfiles[0]),'\\')[-1]
if attachsinglefiledb(targetsql, tgtsa, dbname, tgtpath1):
loginfix(targetsql,tgtsa, dbname, "aspuser")
if connectpath=='*': failsafe = False
else:failsafe = not fgrepcs(sourcesql, dbname, targetsql, connectpath)
else:
if copydb(source,srcfiles[0],target,tgtpath1) and copydb(source,srcfiles[1],target,tgtpath2):
tgtpath1=tgtpath1+'\\'+string.split(string.strip(srcfiles[0]),'\\')[-1]
tgtpath2=tgtpath2+'\\'+string.split(string.strip(srcfiles[1]),'\\')[-1]
if attachdb(targetsql, tgtsa, dbname, tgtpath1, tgtpath2):
loginfix(targetsql,tgtsa, dbname, "aspuser")
if connectpath=='*': failsafe = False
else:failsafe = not fgrepcs(sourcesql, dbname, targetsql, connectpath)
if failsafe: attachdb(sourcesql, srcsa, dbname, srcfiles[0],srcfiles[1])
print "\n*** Done ***"
|