shell脚本操作excle,难度很大,我没有去试验,但是用python搞定了,python连接hive是通过pyhs2客户端(hive官网hiveServe2的安装这一节,python客户端推荐的就是pyhs2),pyhs2四五年之前就停止维护了,github上会推荐你使用pyhive的,这个我用了下,跑复杂的sql报错,没深入研究,就还是用pyhs2,毕竟他是调用hiveServer2来执行任务的,基本和hive-cli是一样的。
hive本身的化就是sql的语句的编写,比较困难的是python对excel的操作和追加,
python本生有一些库,比较好用,最后就是各种测试,直到满足你的需求为止,其中2.7版本的中文编码问题,搞了差不多一天加一晚上,想骂人……,原谅我是没有python基础的人……
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# hive util with hive server2
"""
@author:tianjun
@create:2017年9月25日 20:19:08
"""
__author__ = 'tianjun'
__version__ = '0.1'
import pyhs2
import xlwt
import xlrd
import xlutils
import xlutils.copy
import sys
import smtplib
import email.MIMEMultipart
import email.MIMEText
import email.MIMEBase
import os.path
import mimetypes
import os
import time
import json
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
class Base:
def __init__(self, db_host, user, password, database, port=10000, authMechanism="PLAIN"):
"""
create connection to hive server2
"""
self.conn = pyhs2.connect(host=db_host,
port=port,
authMechanism=authMechanism,
user=user,
password=password,
database=database,
)
def query(self, sql):
"""
query
"""
with self.conn.cursor() as cursor:
cursor.execute(sql)
return cursor.fetch()
def close(self):
"""
close connection
"""
self.conn.close()
def loadJsonAndExec(jsonPath,pyhs2Client,book,fileName,sTime=None,eTime=None):
datas=[]
with open(jsonPath) as json_file:
datas = json.load(json_file)
for data in datas:
cls = data['columnNames'].split(",")
print "columnsNames:" + ",".join(cls)
if sTime:
hql = str(data['hql']).replace("startTime",sTime)
if eTime:
hql = str(data['hql']).replace("endTime",eTime)
print "hql:" + hql
sheetNum = int(data["sheetNum"])
print "sheetNum:" + str(sheetNum)
result = pyhs2Client.query(hql)
print result
#追加
writeXlwt(result=result,book=book,sheetNum=sheetNum,columnNames=cls,isAppend=True,fileName=fileName)
"""
result,查询的结果;
sheetname,sheet名称
book 创建的工作簿
sheetnum,sheet的索引
cloumNames,列的中文名
isAppend,数据是否再excel中追加,默认不追加,
filename,需要追加的excle的路径
"""
def writeXlwt(result,book,columnNames,fileName,sheetNum=None,isAppend=False,sheetName=None):
if isAppend == False:
sheet1=book.add_sheet(sheetName)#添加一个sheet页
for i in range(len(result)+1):
if i ==0:
for j in range(0,len(columnNames)):
sheet1.row(i).write(j,columnNames[j].decode("utf-8"))
if result[i][j] is None:
sheet1.row(i+1).write(j,result[i][j])
else:
sheet1.row(i+1).write(j,str(result[i][j]).decode("utf-8"))
else:
for a in range(len(result[i-1])):
if result[i-1][a] is None:
sheet1.row(i+1).write(a,result[i-1][a])
else:
sheet1.row(i+1).write(a,str(result[i-1][a]).decode("utf-8"))
book.save(fileName)
else:
if fileName:
r_xls = xlrd.open_workbook(fileName)
table = r_xls.sheet_by_index(sheetNum)
w_xls=xlutils.copy.copy(r_xls) #复制表
rows = table.nrows
sheet_write = w_xls.get_sheet(sheetNum)
for i in range(1,len(result)+1):
if i == 1:
for j in range(0,len(columnNames)):
sheet_write.write(rows+i,j,columnNames[j].decode("utf-8"))
if result[i-1][j] is None:
sheet_write.write(rows+i+1,j,result[i-1][j])
else:
sheet_write.write(rows+i+1,j,str(result[i-1][j]).decode("utf-8"))
else:
for k in range(len(result[i-1])):
if result[i-1][k] is None:
sheet_write.write(rows+i+1,k,result[i-1][k])
else:
sheet_write.write(rows+i+1,k,str(result[i-1][k]).decode("utf-8"))
w_xls.save(fileName)
#各种元素的邮件
def sendEmail(receivers,emailSubject,emailBody,sender=None,password=None,smtpServer=None,attachPath=None):
"""
send E-mail
"""
if sender is None:
sender ="***@163.com"
if password is None:
password="***"
if smtpServer is None:
smtpServer="smtp.163.com"
server = smtplib.SMTP(smtpServer)
server.login(sender,password) #仅smtp服务器需要验证时
# 构造MIMEMultipart对象做为根容器
main_msg = email.MIMEMultipart.MIMEMultipart("alternative")
# 构造MIMEText对象做为邮件显示内容并附加到根容器
text =""
html = """
尊敬的用户:
%s
"""% emailBody
text_msg = email.MIMEText.MIMEText(text,"plain",_charset="utf-8")
text_msg2 = email.MIMEText.MIMEText(html,"html",_charset="utf-8")
main_msg.attach(text_msg)
main_msg.attach(text_msg2)
if attachPath:
# 构造MIMEBase对象做为文件附件内容并附加到根容器
ctype,encoding = mimetypes.guess_type(attachPath)
if ctype is None or encoding is not None:
ctype='application/octet-stream'
maintype,subtype = ctype.split('/',1)
## 读入文件内容并格式化
data = open(attachPath, 'rb')
file_msg = email.MIMEBase.MIMEBase(maintype, subtype)
file_msg.set_payload(data.read( ))
data.close( )
email.Encoders.encode_base64(file_msg)
## 设置附件头
basename = os.path.basename(attachPath)
file_msg.add_header('Content-Disposition', 'attachment', filename = basename)
main_msg.attach(file_msg)
# 设置根容器属性
main_msg['From'] = sender
main_msg['To'] = ",".join(receivers)
main_msg['Subject'] = u"%s"% emailSubject
main_msg['Date'] = email.Utils.formatdate( )
# 得到格式化后的完整文本
fullText = main_msg.as_string( )
# 用smtp发送邮件
try:
server.sendmail(sender, receivers, fullText)
finally:
server.quit()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# hive util with hive server2
"""
@author:tianjun
@create:2017年9月25日 20:19:08
"""
__author__ = 'tianjun'
__version__ = '0.1'
import pyhs2
import xlwt
import sys
import os
import datetime # 提供操作日期和时间的类
import base.base as mybase
import traceback
import json
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
def main():
"""
main process
"""
today = datetime.date.today()
print "logs time : " + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
yesterday = today - datetime.timedelta(days=1)
try:
client = mybase.Base(db_host='172.25.30.105', port=10000, user='root', password='test',database='default', authMechanism='PLAIN')
book=xlwt.Workbook() #打开一个工作薄
filename="tianjun.xls"
####这个地方需要注意,必须先新建所有的sheet在最后追加;如果,新建sheet1-追加sheet1-新建sheet2,会导致追加sheet1的内容丢失
# 新建sheet1
mybase.writeXlwt(result=[],book=book,columnNames=[],sheetName=u"新增用户1",fileName=filename)
mybase.writeXlwt(result=[],book=book,columnNames=[],sheetName=u"新增用户2",fileName=filename)
mybase.writeXlwt(result=[],book=book,columnNames=[],sheetName=u"新增用户3",fileName=filename)
mybase.writeXlwt(result=[],book=book,columnNames=[],sheetName=u"新增用户4",fileName=filename)
"""
jsonfile, json文件路径
pyhs2Clinet, pyhs2客户端
book, excel工作簿
fileName,excel路径
sTime=None, 时间范围开始(json里面一定要用startTime)
eTime=None, 时间范围结束(json里面一定要用endTime)
"""
print "yesterday:"+yesterday.strftime("%Y%m%d")
#追加
mybase.loadJsonAndExec(jsonPath="./json/example.json",pyhs2Client=client,book=book,fileName=filename,sTime=yesterday.strftime("%Y%m%d"))
client.close()
print u"hive执行成功"
e_receivers=["***@163.com"]
e_subject=today.strftime('%Y-%m-%d')+u"日报"
e_body=u"详情内容请参见附件"
e_attachPath="test.xls"
mybase.sendEmail(receivers=e_receivers,emailSubject=e_subject,emailBody=e_body,attachPath=filename)
print u"邮件发送成功"
os.remove(filename)
except Exception, e:
e_receivers=["****@163.com"]
e_subject=today.strftime('%Y-%m-%d')+u"日报采集脚本错误"
e_body=u"日报采集脚本抛出异常,具体请参考日志信息!"
mybase.sendEmail(receivers=e_receivers,emailSubject=e_subject,emailBody=e_body)
print u"hive执行失败|python操作excel失败|者邮件发送失败"
traceback.print_exc()
sys.exit(1)
if __name__ == '__main__':
main()
[
{
"columnNames":"用户号码","sheetNum":"0","hql":"select user_id from t_di_trace_event_d where dayid ='startTime' and tag='LifeHome_Album' limit 10"
}
]