本帖最后由 ciasdmxhxjjpd@c 于 2022-7-17 09:22 编辑
RT,
以 vultr 为例,其他 vps 同理,只要支持 api,查看 api 文档,适当修改。
pycharm 调试
import requests
import json
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
from requests.structures import CaseInsensitiveDict
# http get
url = 'https://api.vultr.com/v2/'
VULTR_API_KEY = ''
total = 0
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
headers["Authorization"] = "Bearer " + VULTR_API_KEY
# mqtt broker
broker_address = "broker.hivemq.com"
port = 1883
# get first instant id
def get_instance():
getInstance = json.loads(requests.get(url + 'instances', headers=headers).content)
instanceId = getInstance['instances'][0]['id']
return instanceId
# billing
accountInfo = json.loads(requests.get(url + 'account', headers=headers).content)
billing = accountInfo['account']['pending_charges']
balance = accountInfo['account']['balance']
# data use
getInstanceBandwidth = requests.get(url + 'instances/' + get_instance() + '/bandwidth', headers=headers).content
bandwidth = json.loads(getInstanceBandwidth)['bandwidth']
for key in bandwidth:
total = total + bandwidth[key]['incoming_bytes']
# json out
js = {
"billing": billing,
'balance': balance,
"traffic": total
}
message = json.dumps(js)
print(message)
# mqtt broker
publish.single("vps/vultr/billing_and_traffic", payload=message, qos=1, retain=1, hostname=broker_address,
port=port, client_id="", keepalive=60, will=None, auth=None, tls=None,
protocol=mqtt.MQTTv311, transport="tcp")
https://gist.github.com/0neday/68c0003514180cc00b2916f2b7ef2483
然后,在nr里获取,再推给本地的mqtt broker,再在 configuration里配置。
- platform: mqtt
name: "vultr network traffic"
unique_id: vultr_network_traffic
state_topic: "vps/vultr/billing_and_traffic"
value_template: "{{ value_json.traffic | multiply(1.0/1073741824) | round(2) }}"
unit_of_measurement: "GB"
scan_interval: 300
- platform: mqtt
name: "vultr billing"
unique_id: vultr_billing
state_topic: "vps/vultr/billing_and_traffic"
value_template: "{{ value_json.billing }}"
unit_of_measurement: "$"
scan_interval: 1800
- platform: mqtt
name: "vultr balance"
unique_id: vultr_balance
state_topic: "vps/vultr/billing_and_traffic"
value_template: "{{ value_json.balance | abs }}"
unit_of_measurement: "$"
scan_interval: 3600
其次,可以在nr里写各种告警流程。比如流量超了,费用超了等等
|