直接上代码:
#!/usr/bin/python
# _*_coding:utf-8 _*_
import pymysql
import urllib, urllib.request
import json
import requests
import zipfile
import sys
def saveAndzipFile(data, filepath, filename):
file = filepath + filename
print(file)
with open(file, 'w', encoding='utf-8') as f:
f.write('callerid,internetIP,nettype,begintime,calltype,callip,calleeid,calleeip,nexthopid,nexthopip,P2P,endtime,releasetype,isnormal,createtime' + '\n')
for row in data:
temp = ''
for i in range(len(row)):
temp = temp + str(row[i]) + ','
f.write(temp + '\n')
file1 = filepath + 'data.zip'
zip = zipfile.ZipFile(file1, 'w', zipfile.ZIP_DEFLATED)
zip.write(file, filename)
return file1
def gettoken(corpid, corpsecret):
gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
try:
token_file = urllib.request.urlopen(gettoken_url)
except urllib.request.HTTPError as e:
print(e.code)
print(e.read().decode("utf8"))
sys.exit()
token_data = token_file.read().decode('utf-8')
token_json = json.loads(token_data)
token_json.keys()
token = token_json['access_token']
return token
def get_media_id(token, zipf):
url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=' + token + '&type=file'
files = {'file': open(zipf, 'rb')}
r = requests.post(url, files=files)
re = json.loads(r.text)
return re['media_id']
def senddata(access_token, media_id):
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
send_values = {
"toparty": "2", # 企业号中的部门id。
"msgtype": "file", # 消息类型。
"agentid": "1000003", # 企业号中的应用id。
"file": {
"media_id": media_id
},
"safe": "0",
"enable_duplicate_check":"0",
"duplicate_check_interval": "1800"
}
json_post_data=json.dumps(send_values, ensure_ascii=False).encode('utf-8')
r = requests.post(send_url, data=json_post_data, headers={"Content-Type": "application/json; charset=utf-8"})
if __name__ == '__main__':
#value = str(sys.argv[1]) # zabbix传过来的第一个参数
value = 'createtime>DATE_SUB(NOW(), INTERVAL 24 HOUR)'
try:
db1 = pymysql.connect(host='192.168.195.132', user='root', password='zhangyuan', port=3306, db='zabbix',
charset='utf8')
cursor = db1.cursor()
sql = "SELECT * FROM call_info_table WHERE " + value + ";"
cursor.execute(sql)
data = cursor.fetchall()
cursor.close()
db1.close()
except:
print("connect failed!")
file = 'C:/Users/byroot/Desktop/test/data.csv'
zipf = saveAndzipFile(data, filepath='C:/Users/byroot/Desktop/test/', filename='data.csv')
corpid = 'ww700796479a34ae6d' # CorpID是企业号的标识
corpsecret = 'LjAc-x1_mI22oUlAlmrHfRSV4MbHAc3cSjkZpULsaAs' # corpsecretSecret是管理组凭证密钥
accesstoken = gettoken(corpid, corpsecret)
media_id = get_media_id(accesstoken, zipf)
senddata(accesstoken, media_id)
实测成功。