借助wkhtmlpdf命令行工具发送微信图片告警
技术积累 Python wkhtmltopdf

此次是借助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'}

借助wkhtmlpdf命令行工具发送微信图片告警

借助wkhtmlpdf命令行工具发送微信图片告警


本文最后记录时间 2024-03-31
文章链接地址:
https://me.jinchuang.org/archives/280.html
本站文章除注明[转载|引用|来源],均为本站原创内容,转载前请注明出处
使用腾讯云CDN的SDK 用脚本去刷新URL缓存
pip 安装错误 Command "python setup.py egg_info" failed with error code
Linux命令行界面使用Python+Selenium+Chrome对网页截图
warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless

VMware ESXI /vCenter 6.5/6.7

Centos7 安装pip

留言列表

  1. 婚外遇调查
    Windows 7 Google Chrome
    中国江苏省无锡市电信

    用心分享感谢博主

留言

顶部