今天的内容是基于 Python + Flask 实现接口接收内存信息 来进一步分享如何使用 Python + Flask 接收 CPU 的信息。
原理:
通过 Python 调用 Shell 脚本去执行 CPU 的相关信息,然后进行处理再请求 Requests 库来向后端定义好的接口来推送数据。
import os
import requests
import json
import time
url="http://10.8.31.61:5555/GetCpuResource"
cpu_data={}
cpu_cmd = [
"cat /proc/cpuinfo |grep 'processor' |wc -l",
"cat /proc/cpuinfo |grep 'physical id'|sort |uniq |wc -l",
"cat /proc/cpuinfo |grep 'cpu cores'|awk -F' ' '{print $4}' |sort |wc -l",
"uptime |awk -F':' '{print $5}'"
]
def exec_cmd():
for cmd in cpu_cmd:
print(cmd)
response = os.popen(cmd)
if("processor" in cmd):
cpu_data['logic_cpu']=str(response.read()).replace("
","")
elif("physical" in cmd):
cpu_data['physical_cpu']=str(response.read()).replace("
","")
elif("cores" in cmd):
cpu_data['cpu_cores']=str(response.read()).replace("
","")
elif("uptime" in cmd):
cpu_data['cpu_load'] = str(response.read()).replace("
", "")
if (len(cpu_data['cpu_load']) < 3):
response = os.popen("uptime |awk -F':' '{print $4}'")
cpu_data['cpu_load'] = str(response.read()).replace("
", "")
else:
cpu_data['hostname']=str(os.popen("hostname |awk -F'.' '{print $1}' |awk -F'-' '{print $2}'").read()).replace("
","")
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(cpu_data)
time.sleep(3600)
#CPU路由处理
@resource.route('/GetCpuResource',methods=['POST'])
def GetCpuResource():
'''接收来自linux上传的数据'''
query = request.get_json()
hostname = query["hostname"]
logic_cpu = query["logic_cpu"]
physical_cpu = query["physical_cpu"]
cpu_cores = query["cpu_cores"]
cpu_load = query["cpu_load"]
createtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = "insert into cpu_info (hostname,logic_cpu,physical_cpu,cpu_cores,cpu_load,create_time) VALUES "
data = "('" + hostname + "','" + logic_cpu + "','" + physical_cpu + "','" + cpu_cores + "','" + cpu_load + "','" + str(createtime) + "'"
end = data + ")"
sql = sql + end
print(sql)
db = conndb()
db.execute_sql(sql)
data = {'code': 200, 'message': 'success', 'status': '10000'}
return json.dumps(data)
这部分主要分为以下两块内容:
CPU信息
搜索
@resource.route('/getCpuList',methods=['POST'])
def getCpuList():
'''fe的页面列表数据获取'''
query = request.get_json()
print(query)
if (query["hostname"] == ""):
sql1 = "select id,hostname,logic_cpu,physical_cpu,cpu_cores,cpu_load,create_time from cpu_info order by id DESC limit " + str(
(query['pageIndex'] - 1) * query["pageSize"]) + "," + str(query["pageSize"])
count_sql = "select count(*) from mem_info"
colume_sql = "select id from mem_info"
else:
sql1 = "select id,hostname,logic_cpu,physical_cpu,cpu_cores,cpu_load,create_time from cpu_info where hostname like '%" + str(query["hostname"]) + "%' order by id DESC" + " limit " + str(
(query['pageIndex'] - 1) * query["pageSize"]) + "," + str(query["pageSize"])
count_sql = "select count(*) from cpu_info where hostname like '%" + str(
query["hostname"]) + "%' order by id DESC"
colume_sql = "select id from cpu_info"
sql2 = "select id,hostname,logic_cpu,physical_cpu,cpu_cores,cpu_load,create_time from cpu_info"
db = conndb()
listdata = db.get_data(sql1, sql2)
db = conndb()
result = db.get_data(count_sql, colume_sql)
print(result)
pageTotal = result[0]['id']
print(listdata)
print(pageTotal)
data = {'listdata': listdata, "pageTotal": pageTotal, "code": 200}
return json.dumps(data)
页面更新:2024-04-25
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号