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()