一个简单python语言web server,输出机器上的HW信息

有个同学有个简单任务,写一个简单python语言API,从web上访问,输出机器上的HW信息。

然后一起帮忙看看。

其实对这方面一直不太熟悉,一开始不知道怎么下手。然后同事说要写一个web server。于是google了一些网上的代码套用。

代码如下:

from __future__ import print_function

import urllib
import urllib2
import json

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from collections import OrderedDict
class TestHTTPHandler(BaseHTTPRequestHandler):
    def do_GET(self):

        buf = "It works"
        values ={'cpu':cpu_stat(),'mem':memory_stat()}
        jdata = json.dumps(values)
        self.protocal_version = "HTTP/1.1"

        self.send_response(200)

        self.send_header("Welcome", "Contect")

        self.end_headers()

        self.wfile.write(jdata)

def cpu_stat():
    cpu = []
    cpuinfo = {}
    f = open("/proc/cpuinfo")
    lines = f.readlines()
    f.close()
    for line in lines:
        if line == 'n':
            cpu.append(cpuinfo)
            cpuinfo = {}
        if len(line) < 2: continue
        name = line.split(':')[0].rstrip()
        #name = line.split(':')[0] 
        var = line.split(':')[1]
        #var = line.split(':')[1].split()[0]
        cpuinfo[name] = var
    return cpuinfo

def memory_stat():
    mem = {}
    f = open("/proc/meminfo")
    lines = f.readlines()
    f.close()
    for line in lines:
        if len(line) < 2: continue
        name = line.split(':')[0]
        var = line.split(':')[1].split()[0]
        mem[name] = long(var) * 1024.0
    mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
    return mem

def meminfo():
    ''' Return the information in /proc/meminfo
    as a dictionary '''
    meminfo=OrderedDict()

    with open('/proc/meminfo') as f:
        for line in f:
            meminfo[line.split(':')[0]] = line.split(':')[1].strip()
    return meminfo

def start_server(port):
    http_server = HTTPServer(('xx.xx.xx.xx', int(port)), TestHTTPHandler)
    http_server.serve_forever()

if __name__=='__main__':
    start_server(80)
                     

写的还很粗糙。不过可以运行。执行该程序然后访问IP:PROT即可看到输出信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值