今天的内容是基于 Python + Flask 实现接口接收内存信息 来进一步分享如何使用 Python + Flask 接收 CPU 的信息。
原理:
通过 Python 调用 Shell 脚本去执行 CPU 的相关信息,然后进行处理再请求 Requests 库来向后端定义好的接口来推送数据。
Part1:收集端
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("\n","")
elif("physical" in cmd):
cpu_data['physical_cpu']=str(response.read()).replace("\n","")
elif("cores" in cmd):
cpu_data['cpu_cores']=str(response.read()).replace("\n","")
elif("uptime" in cmd):
cpu_data['cpu_load'] = str(response.read()).replace("\n", "")
if (len(cpu_data['cpu_load']) < 3):
response = os.popen("uptime |awk -F':' '{print $4}'")
cpu_data['cpu_load'] = str(response.read()).replace("\n", "")
else:
cpu_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(cpu_data)
time.sleep(3600)
Part2:接收端