您的位置:首页 > 数据库

shell脚本实现查询数据库上传到ftp

2016-10-10 18:51 253 查看
1. python代码:将多行sql合并成一行

#!/usr/bin/python
#encoding:utf-8
import sys

file = open(sys.argv[1])
sql=''
for line in file:
sql += ' ' + line
#print 'sql is ' + sql
result = ' '.join(sql.split())
print 'result is ' + result

2.  配置文件:配置账号和密码

Username=wwh
Password=wwh
IsDeleteFileAfterUpload=1
Sql="select * from user"


3.shell脚本:实现查询数据库,在本地生成文件并上传到ftp

#!/bin/bash
#set -e
baseDir=$(readlink -f $(dirname $0))
now=`date '+%Y-%m-%d %H:%M:%S'`
ahourago=`date '+%H:%M:%S' -d '-1 hours'`
filename=`date '+%Y%m%d%H%M%S'`".csv"
filepath=$baseDir/$filename
echo "$now ::: ftp $filepath"
while read line;do
eval "$line"
done < $baseDir/config
mysql --default-character-set=gbk -Dstrategy -hpslave36 -uroot -proot -e "$Sql" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > $filepath
ftp -i -n <<FTPIT
open $FtpIp
user $Username $Password
put $filepath $filename
quit
FTPIT

if [ $IsDeleteFileAfterUpload -eq 1 ];then
rm -rf $filepath
fi
echo "$now ::: success!"
# exit 0

4.使用crontab配置定时任务

#工作日9点到18点发送文件数据
0 9-23 * * 1-5 sh /uploadfiles/uploadfile.sh >> /logs//ftp.log 2>&1 &
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell python 脚本 ftp sql