三年前写的,这个是Linux版本的 还有个windows版,具体场景不记得了,但可以做参考
获取ip、解析json、输出文件
# -*- coding: UTF-8 -*-
import requests
import os
import socket
import re
'''
获取ip
'''
def get_ip():
with os.popen('ifconfig') as cmd:
str = cmd.readlines()
data = str[1].strip()
if not data.__contains__("inet 10.10"):
raise ValueError("没有符合规则的ip inet 10.10")
return re.search('inet (10.10.[\d]{1,3}.[\d]{1,3})', data).group(1)
'''
接口调用---解析json
'''
def get_json():
# 调获取本机名方法
# 请求地址,主机名不可写死
url = "https://tws.com/r/global//v1/hosting/machine?computerName=%s" %(socket.gethostname())
# 发送get请求获取返回的json数据
r = str(requests.get(url).json())
if not r.__contains__("firewallIp"):
raise ValueError("未获取到防火墙IP")
return r
'''
输出为custom_data.prom文件
'''
def make_file(ip, firewallip, port):
with open('/home//node_exporter/textfile/custom_data.prom', 'w', encoding="utf-8") as f: # 覆盖显示
f.write('textfile_windows_meta { ip="%s", firewall="%s", machinetype="宿主机", cabinet="%s" } 1\n' % (ip, firewallip, port))
print("ok")
def main():
try:
# ip = get_ip()
firewallip = re.search('firewallIp\': \'([\d]{1,3}.[\d]{1,3}.[\d]{1,3}.[\d]{1,3})', get_json()).group(1)
port = re.search('rackNumber\': (\'A[\d]{1,3})', get_json()).group(1)
make_file(get_ip(), firewallip, port)
except Exception as e:
print(e)
main()