python下载腾讯云慢日志并发送邮件附件
这里没优化,只是对腾讯云下载慢日志,然后通过邮件发送出去 #!/usr/bin/env python # encoding: utf-8 import json import smtplib import urllib2 from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart from QcloudApi.qcloudapi import QcloudApi from datetime import timedelta, datetime yesterday = datetime.today() + timedelta(-1) yesterday_format = yesterday.strftime('%Y%m%d') log_test1_dir = '/data/logsbak/slowlog/test1/' log_test2_dir = '/data/logsbak/slowlog/test2/' def download(url,filename): url = url f = urllib2.urlopen(url) data = f.read() with open(filename, "wb") as code: code.write(data) def sendmail(sender,password,receivers,smtpServer,subject,content,file1,file2): sender = sender password = password receivers = receivers smtp_server = smtpServer message = MIMEMultipart() message['From'] = sender message['To'] = ','.join(receivers) message['Subject'] = subject message.attach(MIMEText(content, 'plain', 'utf-8')) file_test1 = log_test1_dir + file1 file_test2 = log_test2_dir + file2 att1 = MIMEText(open(file_test1, 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename=%s' %file1 message.attach(att1) att2 = MIMEText(open(file_test2, 'rb').read(), 'base64', 'utf-8') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename=%s' %file2 message.attach(att2) server = smtplib.SMTP(smtp_server,25) #server.set_debuglevel(1) server.login(sender,password) server.sendmail(sender,receivers,message.as_string()) server.quit() def qcloud_cdb_log(SecretId,SecretKey,Region): module = 'cdb' action = 'GetCdbExportLogUrl' action_params = { 'cdbInstanceId':'cdb-l2lpuyjt', 'type':'slowlog_day', } config = { 'Region': Region, 'secretId': SecretId, 'secretKey': SecretKey, } try: service = QcloudApi(module, config) cdb = json.loads(service.call(action, action_params)) return cdb['data'] except Exception as e: import traceback print('traceback.format_exc():\n%s' % traceback.format_exc()) if __name__ == '__main__': cdb_data = qcloud_cdb_log('sjsldjflsjdfljsljdljwejjlwjkljlwer','sldjflsjdlfjsljdfljsljfldkjslfjldsjlfjdslf','ap-beijing') logname_test1 = cdb_data[-2]['file_name'] link_test1 = cdb_data[-2]['out_url'] slowlog_test1 = log_test1_dir + logname_test1 logname_test2 = 'test2_slowlog_' + yesterday_format + '.log' download(link_test1,slowlog_test1) sender = 'jiankong@test.com' #receivers = ['lw@test.com'] receivers = ['xb@test.com'] password = '123456' smtpServer = 'smtp.test.com' subject = '慢日志' content = '慢日志,请查看附件' sendmail(sender,password,receivers,smtpServer,subject,content,logname_test1,logname_test2)