python-探测服务器端口存活状态并推送至钉钉机器人

python-探测服务器端口存活状态推送钉钉机器人

只会在端口开启或者关闭状态改变时推送消息哦

以下是代码

#-*- coding: utf-8 -*-
# !/usr/bin/python3

import dingtalkchatbot.chatbot as cb
import datetime
import sys
import platform
import socket
import time

portStatus = False
Today = datetime.datetime.now().strftime('%Y%m%d')
Hour = datetime.datetime.now().strftime('%Y年%m月%d日%H时')

os = platform.system()
if os == 'Windows':
    path_day = "E:\\ls\\portup.txt"
    path_down = "E:\\ls\\portdown.txt"
else:
    path_day = "/home/py/portup.txt"
    path_down = "/home/py/portdown.txt"


class dingRobot():

    def __init__(self,filepath):
        self.url = "https://oapi.dingtalk.com/robot/send?access_token=填写Webhook 地址"
        self.path = filepath

    def getMessage(self):
        message = ""
        print(self.path)
        for line in open(self.path, encoding="utf-8", errors="ignore"):
            message = message + line
        return message
    def getMessageshutdown(self):
        getMessageshutdown = ""
        print(self.path)
        for line in open(self.path, encoding="utf-8", errors="ignore"):
            getMessageshutdown = getMessageshutdown + line
        return getMessageshutdown


    def dingStart(self):
        msg = self.getMessage()
        xiaoding = cb.DingtalkChatbot(self.url)
        xiaoding.send_text(msg=msg + Hour)
    
    def dingStart2(self):
        msgdown=self.getMessageshutdown()
        xiaoding = cb.DingtalkChatbot(self.url)
        xiaoding.send_text(msg=msgdown + Hour)


if __name__ == "__main__":
    while True:
        time.sleep(6)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex(('填写IP或者域名',填写端口号))
        sock.close()
        if result == 0:
            if not portStatus:
                print('100.1端口开启')
                #dingding = dingRobot(path_day)
                dingding = dingRobot(path_day)
                dingding.dingStart()
                portStatus =True

        elif result != 0 :
            if portStatus:                   
                print("100.1端口关闭,return code:%s" % result)#这里100.1是顶顶的安全验证信息
                dingding = dingRobot(path_down)
                dingding.dingStart2()
                portStatus =False
        else:
            print()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值