一、前言
剛剛開始學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!!'
三、測試
[linuxidc@ www.linuxidc.com ~]$ ./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!