一、前言
刚刚开始学python,还在看一套简单的python教学视频,但还未看完,简单的写了个mysql备份脚本,也算是第一个python脚本的×××座哈~~,因为才刚刚才开始,对python 的class 、function、build-in function 、模块 等等,怎么使用,什么时候使用都没什么概念 ,由于第一个,所以仅此记录一下吧,也欢迎路过的pythoner赐教。
二、脚本
环境:Centos 6.3
Python 2.6.6
脚本如下:
#!/usr/bin/env python
# author: kuangl
# -*- coding: utf-8 -*-
# filename: mysql_back_zhubao.py
import os
import time
import string
''' defined variable '''
databases=['kaixin']
sql_user='root'
sql_pwd=['kwqsk123p;/$']
''' Defining the remote backup variables '''
jv_test01_ip="192.168.1.16"
jv_test01_user="kuangl"
jv_test01_port='61239'
jv_test01_dir="/home/kuangl/zhubao_mysql/"
''' Create the backup file directory '''
mkdir_dir="/home/kuangl/backup/jewelvary/"+time.strftime('%Y%m')+"/"
if not os.path.exists(mkdir_dir):
os.mkdir(mkdir_dir)
print 'Successfully created directory', mkdir_dir
''' Start backup of database to the specified directory '''
for database_name in databases:
os.chdir(mkdir_dir)
today_sql=mkdir_dir+database_name+'_'+time.strftime('%Y%m%d')+'.sql'
sql_comm="mysqldump -u %s -p'%s' %s > %s"%(sql_user,sql_pwd[0],database_name,today_sql)
if os.system(sql_comm) == 0:
print database_name,'is backup successfully!'
else:
print database_name,'is backup Failed!!'
time.sleep(3)
scp_comm="scp -P%s %s %s@%s:%s "% (jw_admin_port,today_sql,jw_admin_user,jw_admin_ip,jw_admin_dir)
if os.system(scp_comm) == 0:
print today_sql,'This file backup to jv_test01 success!'
else:
print today_sql,'This file backup to jv_test01 Failed!!'
三、测试
[kuangl@jv-test01 ~]$ ./mysql_back_zhubao.py
kaixin is backup successfully!
kaixin_20130806.sql 100% 1997KB 2.0MB/s 00:00
/home/kuangl/backup/jewelvary/201308/kaixin_20130806.sql This file backup to jv-test01 success!