阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Python获取服务端口存活状态并报警

384次阅读
没有评论

共计 4497 个字符,预计需要花费 12 分钟才能阅读完成。

最近发现公司的测试环境中有个 Socket 服务的端口总是莫名其妙 Down 掉,但是服务却正常运行着,看样子是僵死了。

虽然是测试环境,但是也不能这样放着不管,于是连夜写了一个简单的监控脚本。因为服务器是 Windows 的,所以要用到 wmi 模块。逻辑如下:

1、用 wmi 模块获取系统中处于停止状态的服务,生成一个字典。

2、判断监控的服务是否存在于字典中,如果存在说明服务已经停止,那么将尝试启动服务,并发送报警邮件。

3、向本地的 Socket 服务端口发送一个 connect,如果捕获到异常将尝试重启服务,并发送报警邮件。

4、每次执行时脚本将会循环执行以上步骤三次,间隔 10 秒,以确保服务状态正常。

在运行的时候发现了一个问题,Python 使用 wmi 模块来对 Windows 系统进行操作的时候速度格外的慢,不知道有没有其他的代替方法,哪位如果有更好的方法可以指点一下。

源码如下:

#!/usr/bin/env python

import os
import wmi
import time
import socket
import base64
import smtplib
import logging
from email.mime.text import MIMEText


def get_stop_service(designation):
    """Get stopped service name and caption,
    Filtration 'designation' service whether there is 'Stopped'.

    :return: service state
    """
    c = wmi.WMI()
    ret = dict()
    for service in c.Win32_Service():
        state, caption = service.State, service.Caption
        if state == 'Stopped':
            t = ret.get(state, [])
            t.append(caption)
            ret[state] = t
    # If 'designation' service in the 'Stopped', return status is 'down'
    if designation in ret.get('Stopped'):
        logging.error('Service [%s] is down, try to restart the service. \r\n' % designation)
        return 'down'
    return True


def monitor(sname):
    """Send the machine IP port 20000 socket request,
    If capture the abnormal returns the string 'ex'.

    :return: string 'ex'
    """
    s = socket.socket()
    s.settimeout(3)  # timeout
    host = ('127.0.0.1', 20000)
    try:  # Try connection to the host
        s.connect(host)
    except socket.error as e:
        logging.warning('[%s] service connection failed: %s \r\n' % (sname, e))
        return 'ex'
    return True


def restart_service(rstname, conn, run):
    """First check whether the service is stopped,
    if stop, start the service directly.
    The check whether the zombies,
    if a zombie, then restart the service.

    :return: flag or True
    """
    flag = False
    try:
        # From get_stop_service() to obtain the return value, the return value
        if run == 'down':
            ret = os.system('sc start"%s"' % rstname)
            if ret != 0:
                raise Exception('[Errno %s]' % ret)
            flag = True
        elif conn == 'ex':
            retStop = os.system('sc stop"%s"' % rstname)
            retSart = os.system('sc start"%s"' % rstname)
            if retSart != 0:
                raise Exception('retStop [Status code %s] '
                                'retSart [Status code %s] ' % (retStop, retSart))
            flag = True
        else:
            logging.info('[%s] service running status to normal' % rstname)
            return True
    except Exception as e:
        logging.warning('[%s] service restart failed: %s \r\n' % (rstname, e))
        return flag


def send_mail(to_list, sub, contents):
    """Send alarm mail.

    :return: flag
    """
    mail_server = 'mail.stmp.com'  # STMP Server
    mail_user = 'YouAccount'  # Mail account
    mail_pass = base64.b64decode('Password')  # The encrypted password
    mail_postfix = 'smtp.com'  # Domain name

    me = 'Monitor alarm<%s@%s>' % (mail_user, mail_postfix)
    message = MIMEText(contents, _subtype='html', _charset='utf-8')

    message['Subject'] = sub
    message['From'] = me
    message['To'] = ';'.join(to_list)

    flag = False  # To determine whether a mail sent successfully
    try:
        s = smtplib.SMTP()
        s.connect(mail_server)
        s.login(mail_user, mail_pass)
        s.sendmail(me, to_list, message.as_string())
        s.close()
        flag = True
    except Exception, e:
        logging.warning('Send mail failed, exception: [%s]. \r\n' % e)

    return flag


def main(sname):
    """Parameter type in the name of the service need to monitor,
    perform functions defined in turn, and the return value is correct.
    After the program is running, will test three times,
    each time interval to 10 seconds.

    :return: retValue
    """
    retry = 3
    count = 0
    retValue = False  # Used return to the state of the socket
    while count < retry:
        ret = monitor(sname)
        if ret != 'ex':  # If socket connection is normaol, return retValue
            retValue = ret
            return retValue
        isDown = get_stop_service(sname)
        restart_service(rstname=sname, conn=ret, run=isDown)

        host = socket.gethostname()
        address = socket.gethostbyname(host)
        mailto_list = ['mail@smtp.com', ]  # Alarm contacts
        send_mail(mailto_list, 
                  'Alarm',
                  ' <h4>Level: <u>ERROR</u></br> Host name: %s</br>'
                  ' IP Address: %s</br>'
                  ' Service name:</h4> <h5>%s</h5>'
                  % (host, address, sname))
        count += 1
        time.sleep(10)
    else:
        logging.error('[%s] service try to restart more than three times \r\n' % sname)

    return retValue


if __name__ == '__main__':

    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)s %(message)s',
                        datefmt='%Y/%m/%d %H:%M:%S',
                        filename='D:\\logs\\Monitor.log',
                        filemode='ab')

    name = 'Service Name'
    response = main(name)
    if response:
        logging.info('The [%s] service connection is normal \r\n' % name)

以上代码还是有可以改进的地方,将多个服务名写到文件中,程序去读取文件中的服务依次进行检测。

Ubuntu 14.04 安装 Python 3.3.5  http://www.linuxidc.com/Linux/2014-05/101481.htm

CentOS 上源码安装 Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python 核心编程 第二版》.(Wesley J. Chun).[高清 PDF 中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python 开发技术详解》.(周伟, 宗杰).[高清 PDF 扫描版 + 随书视频 + 代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python 脚本获取 Linux 系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在 Ubuntu 下用 Python 搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的详细介绍 :请点这里
Python 的下载地址 :请点这里

本文永久更新链接地址 :http://www.linuxidc.com/Linux/2016-09/135620.htm

正文完
星哥玩云-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-21发表,共计4497字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中

星哥玩云

星哥玩云
星哥玩云
分享互联网知识
用户数
4
文章数
19356
评论数
4
阅读量
8321464
文章搜索
热门文章
星哥带你玩飞牛NAS-6:抖音视频同步工具,视频下载自动下载保存

星哥带你玩飞牛NAS-6:抖音视频同步工具,视频下载自动下载保存

星哥带你玩飞牛 NAS-6:抖音视频同步工具,视频下载自动下载保存 前言 各位玩 NAS 的朋友好,我是星哥!...
星哥带你玩飞牛NAS-3:安装飞牛NAS后的很有必要的操作

星哥带你玩飞牛NAS-3:安装飞牛NAS后的很有必要的操作

星哥带你玩飞牛 NAS-3:安装飞牛 NAS 后的很有必要的操作 前言 如果你已经有了飞牛 NAS 系统,之前...
星哥带你玩飞牛NAS-7:手把手教你免费内网穿透-Cloudflare tunnel

星哥带你玩飞牛NAS-7:手把手教你免费内网穿透-Cloudflare tunnel

星哥带你玩飞牛 NAS-7:手把手教你免费内网穿透 -Cloudflare tunnel 前言 大家好,我是星...
星哥带你玩飞牛NAS-2:飞牛配置RAID磁盘阵列

星哥带你玩飞牛NAS-2:飞牛配置RAID磁盘阵列

星哥带你玩飞牛 NAS-2:飞牛配置 RAID 磁盘阵列 前言 大家好,我是星哥之前星哥写了《星哥带你玩飞牛 ...
星哥带你玩飞牛NAS-1:安装飞牛NAS

星哥带你玩飞牛NAS-1:安装飞牛NAS

星哥带你玩飞牛 NAS-1:安装飞牛 NAS 前言 在家庭和小型工作室场景中,NAS(Network Atta...
阿里云CDN
阿里云CDN-提高用户访问的响应速度和成功率
随机文章
300元就能买到的”小钢炮”?惠普7L四盘位小主机解析

300元就能买到的”小钢炮”?惠普7L四盘位小主机解析

  300 元就能买到的 ” 小钢炮 ”?惠普 7L 四盘位小主机解析 最近...
小白也能看懂:什么是云服务器?腾讯云 vs 阿里云对比

小白也能看懂:什么是云服务器?腾讯云 vs 阿里云对比

小白也能看懂:什么是云服务器?腾讯云 vs 阿里云对比 星哥玩云,带你从小白到上云高手。今天咱们就来聊聊——什...
150元打造低成本NAS小钢炮,捡一块3865U工控板

150元打造低成本NAS小钢炮,捡一块3865U工控板

150 元打造低成本 NAS 小钢炮,捡一块 3865U 工控板 一块二手的熊猫 B3 工控板 3865U,搭...
星哥带你玩飞牛NAS-11:咪咕视频订阅部署全攻略

星哥带你玩飞牛NAS-11:咪咕视频订阅部署全攻略

星哥带你玩飞牛 NAS-11:咪咕视频订阅部署全攻略 前言 在家庭影音系统里,NAS 不仅是存储中心,更是内容...
免费无广告!这款跨平台AI RSS阅读器,拯救你的信息焦虑

免费无广告!这款跨平台AI RSS阅读器,拯救你的信息焦虑

  免费无广告!这款跨平台 AI RSS 阅读器,拯救你的信息焦虑 在算法推荐主导信息流的时代,我们...

免费图片视频管理工具让灵感库告别混乱

一言一句话
-「
手气不错
每年0.99刀,拿下你的第一个顶级域名,详细注册使用

每年0.99刀,拿下你的第一个顶级域名,详细注册使用

每年 0.99 刀,拿下你的第一个顶级域名,详细注册使用 前言 作为长期折腾云服务、域名建站的老玩家,星哥一直...
仅2MB大小!开源硬件监控工具:Win11 无缝适配,CPU、GPU、网速全维度掌控

仅2MB大小!开源硬件监控工具:Win11 无缝适配,CPU、GPU、网速全维度掌控

还在忍受动辄数百兆的“全家桶”监控软件?后台偷占资源、界面杂乱冗余,想查个 CPU 温度都要层层点选? 今天给...
欧洲无限速云盘免费10GB永久存储 + WebDAV部署+图床搭建,多平台联动一步到位!

欧洲无限速云盘免费10GB永久存储 + WebDAV部署+图床搭建,多平台联动一步到位!

欧洲无限速云盘免费 10GB 永久存储 + WebDAV 部署 + 图床搭建,多平台联动一步到位! 大家好,我...
4盘位、4K输出、J3455、遥控,NAS硬件入门性价比之王

4盘位、4K输出、J3455、遥控,NAS硬件入门性价比之王

  4 盘位、4K 输出、J3455、遥控,NAS 硬件入门性价比之王 开篇 在 NAS 市场中,威...
开源MoneyPrinterTurbo 利用AI大模型,一键生成高清短视频!

开源MoneyPrinterTurbo 利用AI大模型,一键生成高清短视频!

  开源 MoneyPrinterTurbo 利用 AI 大模型,一键生成高清短视频! 在短视频内容...