靳闯博客 记录是一种习惯,分享是一种态度
  • 波浪
  • 波浪
  • 波浪
  • 波浪
借助wkhtmlpdf命令行工具发送微信图片告警
发表于: | 分类: 技术积累 | 标签: Python wkhtmltopdf | 评论:1 | 阅读: 314

此次是借助wkhtmlpdf工具来发送微信告警

安装使用请参考此篇:wkhtmltopdf - html转pdf/图片命令行工具

准备工具

1、html模板脚本

#!/bin/bash
name="博客域名:jinchuang.org | 磁盘使用情况"
ip=`ifconfig |grep -v 127 |grep inet|awk '{print $2}'`
a=`df -hT|grep -w "/"|awk '{print $1}'`
b=`df -hT|grep -w "/"|awk '{print $2}'`
c=`df -hT|grep -w "/"|awk '{print $3}'`
d=`df -hT|grep -w "/"|awk '{print $4}'`
e=`df -hT|grep -w "/"|awk '{print $5}'`
f=`df -hT|grep -w "/"|awk '{print $6}'`
g=`df -hT|grep -w "/"|awk '{print $7}'`

html="<html>
<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">
<head>
<style type=\"text/css\">
table{margin-top:5%;width:500px}
table.gridtable {
    font-family: verdana,arial,sans-serif;
    font-size:14px;
    color:#333333;
    border-width: 1px;
    border-color: #666666;
    border-collapse: collapse;
}
table.gridtable th {
    border-width: 1px;
    padding: 8px;
    background-color: #008eff;
    color:#fff;
}
table.gridtable td {
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #afafaf;
    background-color: #ffffff;
}
table tr:first-child td:first-child, table tr:first-child th:first-child{
  border-top-left-radius: 5px;
}
table tr:first-child td:last-child, table tr:first-child th:last-child{
  border-top-right-radius: 5px;
}
</style>
</head>
<body>
<table class=\"gridtable\" align=center>
<tr>
    <th colspan="7">$name</th>
</tr>
<tr>
    <td>文件系统</td><td>类型</td><td>总共</td><td>已用</td><td>可用</td><td>使用率</td><td>挂载点</td>
</tr>
<tr>
    <td>$a</td><td>$b</td><td>$c</td><td>$d</td><td>$e</td><td style=\"color:red;font-weight:bold\">$f</td><td>$g</td>
</tr>
</table>
</body>
</html>"
echo -e "$html" >/html/df.html

2、python脚本(使用企业微信api来发送,原企业号,现在申请要认证了!)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/10/10 下午2:10
# @Author  : gaogd

import requests
import json
import sys,os
import time

os.system('sh /shell/html/html.sh')
os.system('/usr/local/bin/wkhtmltoimage /html/df.html /tmp/df.png >/dev/null')

class SendPicture(object):

    UploadPictureUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload"
    GetTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    SendTextUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send"

    Corpid = 'wxxxxxxxxxxxxxxx'  #企业ID
    Corpsecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' #应用secret



    @staticmethod
    def _gettoken():
        Url = '%s?corpid=%s&corpsecret=%s' %(SendPicture.GetTokenUrl,SendPicture.Corpid,SendPicture.Corpsecret)
        try:
            token_file = requests.get(url=Url)
        except Exception as e:
            print('err: %s', e)
            sys.exit()

        token_data = token_file.json()
        return token_data['access_token']

    @staticmethod
    def _uploadPicture(filename):
        media_id = None
        if not os.path.exists(filename):
            print('filename not exists')
            return

        file = {'file': open(filename, 'rb')}
        access_token = SendPicture._gettoken()

        Url = "%s?access_token=%s&type=file" % (SendPicture.UploadPictureUrl,access_token)
        ret = requests.post(Url, files=file)
        try:
            print(ret.json(),type(ret.json()))
            if isinstance(ret.json(),dict):
                media_id = ret.json().get('media_id',None)
        except Exception as err:
            print('upload file failed %s' % str(err))

        return  media_id


    @classmethod
    def sendPicture(cls,filename):
        '''

        :param filename:   需要发的图片路径
        :return:
        '''
        madieId = cls._uploadPicture(filename)

        access_token = cls._gettoken()
        send_url = '%s?access_token=%s' % (cls.SendTextUrl,access_token)
        send_values = {
            "touser": 'user',  # 企业号中的用户帐号,如果配置不正常,将按部门发送。
            "toparty": "2",  # 企业号中的部门id
            "msgtype": "image", #消息类型
            "agentid": "2", #应用Agentld
            "image": {
                "media_id": madieId
            },
            "safe": "0"
        }
        print(madieId)
        send_data = json.dumps(send_values)
        send_request = requests.post(send_url, send_data)
        print(send_request.json())



if __name__ == '__main__':

    # weixin = SendPicture.sendText('test')
    weixin = SendPicture.sendPicture('/tmp/df.png')

执行

[root@jinc /html]❤ python img.py 
Loading page (1/2)
Rendering (2/2)                                                    
Done                                                               
{'errcode': 0, 'errmsg': 'ok', 'type': 'file', 'media_id': '3Tll7BCRw6iQmthHtDMoORqIM4-cpl5crp2GGNLpwLbT1OiVFSA_IhmHqiPW6jLjT', 'created_at': '1540181412'} <class 'dict'>
3Tll7BCRw6iQmthHtDMoORqIM4-cpl5crp2GGNLpwLbT1OiVFSA_IhmHqiPW6jLjT
{'errcode': 0, 'errmsg': 'ok', 'invaliduser': 'user'}

weixintu.png
weixintudf.png


商业转载请联系作者获得授权,非商业转载请注明出处,谢谢合作。


如果这篇文章帮助到了你,我感到十分荣幸!

仅有一条评论

  1. 用心分享感谢博主 icon_biggrin.png

或许你不想写点什么·但我依旧在这里

icon_mrgreen.pngicon_neutral.pngicon_twisted.pngicon_arrow.pngicon_eek.pngicon_smile.pngicon_confused.pngicon_cool.pngicon_evil.pngicon_biggrin.pngicon_idea.pngicon_redface.pngicon_razz.pngicon_rolleyes.pngicon_wink.pngicon_cry.pngicon_surprised.pngicon_lol.pngicon_mad.pngicon_sad.pngicon_exclaim.pngicon_question.png2018new_aini_org.png2018new_baobao_thumb.png2018new_erha_org.png2018new_kuxiao_thumb.png2018new_yun_thumb.png2018new_hufen_thumb.png2018new_gui_org.png2018new_xiaoerbuyu_org.png2018new_heixian_thumb.png2018new_wabi_thumb.png2018new_tianping_thumb.png

站点地图 网站地图
豫ICP备17003270号 | Copyright © 2018 💖 靳闯博客
Typecho🍹Sgreen
TOP