|
SmtC: Show me the Code
Ole Peter Smith
Instituto de Matemática e Estatística
Universidade Federal de Goiás
http://www.olesmith.com.br
|
|
Liberdade é um prato facil de comer.
Mas deficil de digerir
Jean-Jaques Rousseau
|
Backup one Database and copy to List of Hosts
Python Listing: ../../backup.db.py.
#!/usr/bin/python
import sys,os,time
basepath="/usr/local/tars/systems"
tarbin="/bin/tar"
rmbin="/bin/rm"
scpbin="/usr/bin/scp"
mkdirbin="/bin/mkdir"
mysqldumpbin="/usr/bin/mysqldump"
from ssh_host import *
def Read_Args():
args=list(sys.argv)
args.pop(0)
src_host=src_db=dest_hosts=None
if (len(args)>0):
src_host=args[0]
args.pop(0)
if (len(args)>0):
src_db=args[0]
args.pop(0)
if (len(args)>0):
dest_hosts=list(args)
if (not src_host or not src_db or not dest_hosts):
print "Insuficient arguments, usage"
print sys.argv[0]+"srcsystem desthost1 ... desthostN"
exit()
rdest_hosts=SSH_Hosts_Alive(dest_hosts)
return src_host,src_db,rdest_hosts
def Run_Command(command):
print "\t"," ".join(command)+":",
res=os.system(" ".join(command))
print res
return res
def Date_Comps_List():
return [
time.strftime("%Y",time.localtime()),
time.strftime("%m",time.localtime()),
time.strftime("%d",time.localtime()),
]
def Out_Path(basepath):
dates=Date_Comps_List()
dates.pop()
return "/".join( [basepath]+ dates )
def Out_Name(host,db):
dates=Date_Comps_List()+["sql"]
comps=[db,host,".".join(dates)]
return "-".join( [db,host,".".join(dates)] )
def Out_Path_Create(basepath,dest_hosts):
mkdircommands=[mkdirbin,"-p"]
path=Out_Path(basepath)
Run_Command(mkdircommands+[path])
for dest_host in dest_hosts:
Run_Command(["/usr/local/sbin/"+dest_host]+mkdircommands+[path])
return path
def Dump_File(basepath,host,db):
dates=Date_Comps_List()
date=".".join(dates)
return "/".join(
[
Out_Path(basepath),
Out_Name(host,db)
]
)
def DB_Dump(basepath,host,db,dest_hosts):
outpath=Out_Path_Create(basepath,dest_hosts)
return Run_Command([
mysqldumpbin,
"--defaults-file=/usr/local/sbin/.my.cnf."+db,
"-h",host,
# "-u","ole",
" --lock-tables=false",
db,
"-r",
Dump_File(basepath,host,db),
])
def Tar_Dump(sqlfile):
tarfile=sqlfile+".tgz"
Run_Command([
tarbin,
"cfz",
tarfile,
sqlfile,
])
Run_Command([rmbin,sqlfile])
return tarfile
def Copy_Dump(tarfile,dest_hosts):
for dest_host in dest_hosts:
Run_Command([
scpbin,
tarfile,
dest_host+":"+tarfile
])
#Execution
#Gather command line args
src_host,src_db,dest_hosts=Read_Args()
print "###"
print "### Running MySQL DB backup,",src_host+":"+src_db,"to",", ".join(dest_hosts)
print "###"
os.system("/bin/date")
#Create destination paths and do the dump
res=DB_Dump(basepath,src_host,src_db,dest_hosts)
if (res!=0):
print "Error dumping database "+src_host+":"+src_db
exit()
sqlfile=Dump_File(basepath,src_host,src_db)
#Tar dumpfile
tarfile=Tar_Dump(sqlfile)
#Copy tarfile to destination hosts
Copy_Dump(tarfile,dest_hosts)
print "###"
print "### Done, MySQL DB backup,",src_host+":"+src_db,"to",", ".join(dest_hosts)
print "###\n"
|
|
Messages:
0 secs.
|