今天分享的内容是基于:Python + Flask 实现接口接收内存信息 来进一步分享如何使用 Python + Flask 实现接收 Disk 的信息。
原理:
通过 Python 调用 Shell 脚本去执行 Disk 的相关命令,然后进行处理再请求 Requests 库来向后端定义好的接口推送数据。
Part1:收集端
import os
import requests
import json
import time
url="http://10.8.31.61:5555/GetDiskResource"
mem_data={}
mem_cmd = [
"df -h |grep home |awk -F' ' '{print $2}'",
"df -h |grep home |awk -F' ' '{print $3}'",
"df -h |grep home |awk -F' ' '{print $4}'"
]
def exec_cmd():
for cmd in mem_cmd:
print(cmd)
response = os.popen(cmd)
if("$2" in cmd):
mem_data['total']=str(response.read()).replace("\n","")
elif("$3" in cmd):
mem_data['used']=str(response.read()).replace("\n","")
elif("$4" in cmd):
mem_data['available']=str(response.read()).replace("\n","")
else:
mem_data['hostname']=str(os.popen("hostname |awk -F'.' '{print $1}' |awk -F'-' '{print $2}'").read()).replace("\n","")
response.close()
def httpPost(datas):
header = {"Content-Type":"application/json"}
resp_content = requests.post(url=url,data=json.dumps(datas),headers=header)
print(resp_content.text)
if __name__ == '__main__':
while True:
exec_cmd()
httpPost(mem_data)
time.sleep(3600)
Part2:接收端
#磁盘路由处理-------------------------------------------------------
@resource.route('/GetDiskResource',methods=['POST'])
def GetDiskResource():
'''接收来自linux上传的数据'''
query = req