Python + Flask 实现接口接收 CPU 信息

今天的内容是基于 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:接收端

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wu_Candy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值