Python休印机告警

葛大爷 互联网 2022-09-26 85
# !/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
#
# Copyright (c) 2022 nidayed.net, Inc. All Rights Reserved
#
################################################################################
"""
打印机告警
Authors: gedaye
Date: 2022年9月26日
"""
import urllib
import urllib.request
import urllib.parse
import http.cookiejar
import json

LOGIN_URL = "http://XXX/PrintWebNew"
GET_LIST_URL = "http://XXX/PrintWebNew/SNMP/GetList"
DING_URL = "https://oapi.dingtalk.com/robot/send?access_token=XXX"
HTTP_COOKIE = http.cookiejar.CookieJar()
HTTP_HANDLER = urllib.request.HTTPCookieProcessor(HTTP_COOKIE)
HTTP_OPENER = urllib.request.build_opener(HTTP_HANDLER )

def login_cookie():
params = init_params()
encode_params = urllib.parse.urlencode(params).encode("utf-8")
headers = {
'Cookie': 'KeyValue=XXX'
}
http_request = urllib.request.Request(LOGIN_URL, data=encode_params,headers=headers)
http_response = HTTP_OPENER.open(http_request)
response_html = http_response.read().decode()
return HTTP_COOKIE

def init_params():
params = dict()
params["enusername"] = "XXX"
params["enpassword"] = "XXX"
return params

def init_params2():
params = dict()
params["pageIndex"] = 1
params["pageSize"] = 20
params["searchKey"] = ""
params["SortingByName"] = "ModelName"
params["SortingMethod"] = "asc"
params["Deleted"] = 0
return params

def get_list():
cookie_storage = login_cookie()
login_handler = urllib.request.HTTPCookieProcessor(cookie_storage)
login_opener = urllib.request.build_opener(login_handler)
params = init_params2()
encode_params = urllib.parse.urlencode(params).encode("utf-8")
http_request = urllib.request.Request(GET_LIST_URL, data=encode_params)
response = login_opener.open(http_request)
data = response.read().decode()
data_json = json.loads(data)
for item in data_json['items']:
IP=item['IP']
TonerYellow=item['TonerYellow']
TonerRed=item['TonerRed']
TonerCyan=item['TonerCyan']
TonerBlack=item['TonerBlack']
if IP=="XXX":
local="北京B3"
elif IP=="XXX":
local="北京B2"
elif IP=="XXX":
local="北京A3"
elif IP=="XXX":
local="北京A2"
elif IP=="XXX":
local="上海"
else:
local="武汉"
if int(TonerYellow) <=20 or int(TonerRed) <=20 or int(TonerCyan) <=20 or int(TonerBlack) <=20:
content="打印机:"+IP+"\n位置:"+local+"\n黄色墨盒:"+TonerYellow+"\n红色墨盒:"+TonerRed+"\n青色墨盒:"+TonerCyan+"\n黑色墨盒:"+TonerBlack
print_alert(content)

def print_alert(content):
payload={"msgtype": "text","text":{"content":content}}
files=[]
headers = {"Content-Type":"application/json"}
response = requests.request("POST", DING_URL, headers=headers, json=payload, files=files)
print(response.text)

if __name__ == "__main__":
get_list()