脚本编程

SendCloud邮件队列状态和已使用额度的Python监控脚本

Jager · 3月29日 · 2015年 · · 3909次已读

公司最近用上了 SendCloud 的邮件代发服务,于是就有了各种监控需求。比如每天发信额度是不是要超标了或是邮件是否堵塞了等等。最近经常接触 python,所以这次也一样,继续学习使用 python 来完成各种脚本需求。

SendCloud邮件队列状态和已使用额度的Python监控脚本

SendCloud 提供了很多对外查询的 API,只要 Get 或 Post 传递用户名和 KEY 即可获得想要的各种数据,比如最简单的【已使用额度】就可以在用户信息 json 接口查询。

文档地址:http://sendcloud.sohu.com/doc/email/user_info/

调用形式如下:

http://sendcloud.sohu.com/webapi/userinfo.get.json?api_user=***&api_key=***

返回示例如下:

{
    "message": "success",
    "userinfo": {
        "quota": 5700,
        "usedQuota": 0,
        "reputation": 65.768845,
        "balance": 0,
        "availableBalance": -2.9,
        "userName": "sendcloud_admin",
        "accountType": "付费用户",
        "regTime": "2013-01-01"
    }
}

其中的 usedQuata 就是我所要监控的当前使用额度了。 先用我目前比较熟悉的 php 写一个脚本试试:

<?php
    $data = file_get_contents('http://sendcloud.sohu.com/webapi/userinfo.get.json?api_user=username&api_key=userkey');
    $data = json_decode($data,true); 
    $userinfo=$data["userinfo"];
    $usedQuota = $userinfo["usedQuota"];
    echo $usedQuota;
    exit;
?>

这样就可以输出当前的使用额度了,然后放到 zabbix 配置文件中即可 ,记得要使用 php 调用哦。

下面再试试我还不太熟悉的 python,目的很简单,在提高性能的同时学习一下自己的弱项,代码很稚嫩估计内行一看就知道是新手写的,仅供参考。。。

#coding=utf-8
#!/usr/bin/env python
#SendCloud 当前使用额度和邮件队列是否阻塞监控脚本
#代码中的 username 和 userkey 需要修改为实际对应
#执行形式为:脚本.py -r usedQuota/isStop
#usedQuota 表示查询当前使用额度,isStop 查询是否存在暂停的队列

#转载所需组件
import optparse
import json
import httplib

#GET 抓取 JSON 返回值并转换为字典
def GetData(url):
    conn = httplib.HTTPConnection("sendcloud.sohu.com")
    conn.request(method="GET",url=url) 
    response = conn.getresponse()
    if response.reason != 'OK':
        print 404
        exit()
    res= response.read()
    data = json.loads(res)
    conn.close()
    return data

#定义执行选项
choices = ['usedQuota','isStop']
parser = optparse.OptionParser()
parser.add_option('-r', '--run', type='choice', choices=choices)
(options, args) = parser.parse_args()
if not options.run: parser.error('Please run with Usg like script.ye -r isStop')
if options.run == 'usedQuota':
    #监控 SendCloud 当前请求额度
    url = "http://sendcloud.sohu.com/webapi/userinfo.get.json?api_user=username&api_key=userkey"
    print GetData(url)['userinfo']['usedQuota']
elif options.run == 'isStop':
    #监控 SendCloud API_USER 发送队列是否暂停,若暂停则输出未处理的邮件总数,正常情况下则输出 0
    url = "http://sendcloud.sohu.com/webapi/queueStatus.get.json?api_user=usename&api_key=userkey"
    data = GetData(url);
    if data['queueStatus']:
        exp = 0
        for obj in data['queueStatus']:
            if obj['isStop'] == True:
                exp += obj['unRequestNum']
        print exp  
    else:
        print 0

脚本执行形式:

#监控当天使用额度
SendCloud.py -r usedQuota

#监控队列是否暂停
SendCloud.py -r isStop

涉及到了网页抓取,期间少不了百度搜索 python 抓取网站的一些函数和用法,于是继续写了一个监控网页 HTTP 状态码的监控脚本,权当是学习之作:

#coding=utf-8
#!/usr/bin/env python
#网页状态码监控脚本
#若返回码不是 200 或 304 将输出对应数值,正常则输出 200 表示无异常
#执行形式为:脚本.py -r website1/website2

#装载必须组件
import optparse
import httplib
import sys

#屏蔽错误信息
sys.stderr = None

#使用 head 方法获取网页状态码
def GetData(host,url):
    conn = httplib.HTTPConnection(host)
    conn.request(method="HEAD",url=url) 
    response = conn.getresponse()
    return response.status

choices = ['webiste1','website2']
parser = optparse.OptionParser()
parser.add_option('-r', '--run', type='choice', choices=choices)
(options, args) = parser.parse_args()
if not options.run: parser.error('At least one check should be specified')

if options.run == 'website1':
    #监控 Http CODE
    host = "zhang.ge"
    url = "/5028.html"
    http_code = GetData(host,url)
    if  http_code == 200 or http_code == 304:
        print 200
    else:
        print http_code
elif options.run == 'website2':
    host = "zhang.ge"
    url = "/4586.html"
    http_code = GetData(host,url)
    if  http_code == 200 or http_code == 304:
        print 200
    else:
        print http_code

几次接触下来,python 给我的感觉就是不但功能强大,而且简单易懂。基本都可以依葫芦画瓢实现你想要的各种功能。当然,本文分享的几个脚本都是用于 zabbix 监控的,如何添加请参考博客上一篇文章。

另外,SendCloud 的可监控项目非常多,比如今天发了多少邮件,成功了多少,被拦截了多少,无效邮件有多少等等。基本上,官方都提供了相应的查询接口,所以只要参考本文的脚本和思路,相信就能完成你想要的监控脚本。

2 条回应
  1. WingsBlog 2015-4-4 · 14:18

    好高端

  2. 北京seo 2015-4-6 · 16:53

    谢谢你的博客啊,分享了很多知识,我的网站www.aiyw.net