批量備份,刪除MySQL表 python指令碼

2021-09-21 09:57:51 字數 2275 閱讀 6987

批量備份,刪除mysql表(python指令碼)

#!/usr/bin/env python

#coding=utf-8

#本指令碼主要用來批量刪除以rbcn開頭命名,以數字結尾的表。先找出此類表,備份,遠端拷貝(由於本主機的空間不足),刪除本地備份檔案,刪除庫表。

#引入mysql模組

import mysqldb

#引入re(正規表示式)模組

import re

#引入os模組(執行系統命令)

import os

#引入pexpect模組(可以實現通過ssh,ftp等程式自動互動)

import pexpect

#指定連線mysql例項的賬戶,密碼,字符集,及備份目錄

user = 'root'

passwd = '123456'

db = 'db_test'

charset = 'gbk'

cmd = '/usr/bin/mysqldump'

path = '/tmp/'

#指定關於遠端拷貝的相關主機,密碼,目錄等

scp_path = '/usr/bin/scp'

remote_host = '172.31.x.x'

remote_user = 'root'

remote_passwd = '123456'

remote_path = '/mnt/data/mysqlbackup/table_backup/'

#建立乙個連線物件

con = mysqldb.connect(host="localhost", port=3306, user="root", passwd="123456", db="db_test")

#建立游標,所有的查詢,都在連線con的乙個模組cursor上面執行的

cursor = con.cursor()

#檢視資料庫中存在的表名

sql = "show tables"

cursor.execute(sql)

#從游標中取出所有記錄放入乙個元組序列

results = cursor.fetchall()

#通過for迴圈取出元組每個元素(其還是元組)

for result in results:

#取出每個元素的值,引用re模組的match方法做匹配,其中\a代表匹配的開始位置,\z代表匹配的末尾位置,\d代表任意數字。

m2 = re.match(r"\arbcn.*\d\z", result[0])

#判斷m2的值為真,則進行以下處理(也就是匹配到的表)

if m2:

print result[0]

#取出表名

table_name = result[0]

#定義備份此表

backup_cmd = "%s --default-character-set=%s -u%s -p%s %s %s > %s%s" %(cmd,charset,user,passwd,db,table_name,path,table_name)

#執行備份,判斷如果備份成功,做如下處理

if os.system(backup_cmd) == 0:

print 'successful backup',result[0]

#定義遠端拷貝

scp_cmd = "%s %s%s 

%s@%s:%s

" %(scp_path,path,table_name,remote_user,remote_host,remote_path)

#呼叫pexpect的spawn模組,執行scp_cmd命令

scp = pexpect.spawn(scp_cmd)

#密碼驗證

scp.sendline('remote_passwd')

scp.read()

scp.close()

#刪除本地備份檔案

re_file = "%s%s" %(path,table_name)

os.remove(re_file)

#刪除資料庫中此表 

sql2 = "drop table %s" %(table_name)

cursor.execute(sql2)        

else:

print 'failed'

con.close()

#author:lyk

#time:2013/07/23

#added:此指令碼並不完美,如ssh的timeout時間判斷,驗證遠端主機是否已存在備份檔案,md5值驗證等。本環境為線上內網,所以,,,

MySQL批量刪除指定字首表

mysql批量刪除指定字首表 select concat drop table table name,from information schema.tables where table name like dede dede 為要刪除的表字首,執行此sql語句後會生成一串sql語句,必須再執行生成...

MySQL批量刪除指定字首表

select concat drop table table name,from information schema.tables where table name like dede dede 為要刪除的表字首,執行此sql語句後會生成一串sql語句,必須再執行生成的這些sql語句才能真正執行刪...

批量刪除表

批量刪除表 方法1 select truncate table object name from user objects where object name like ky prj temp and object type table command windows 下執行查詢結果 方法2 sel...