Django SimpleCMDB 项目

Stella981
• 阅读 699

创建 SimpleCMDB 项目:

[root@localhost ~]$ django-admin.py startproject SimpleCMDB

创建应用,收集主机信息:

[root@localhost ~]$ cd SimpleCMDB/
[root@localhost SimpleCMDB]$ python manage.py startapp hostinfo

修改配置:

[root@localhost SimpleCMDB]$ cat SimpleCMDB/settings.py

INSTALLED_APPS = (    # 添加应用
    ......
    'hostinfo',
)

MIDDLEWARE_CLASSES = (    # 禁用CSRF,使得可以使用POST传递数据
    ......
    #'django.middleware.csrf.CsrfViewMiddleware',
)

LANGUAGE_CODE = 'zh-cn'    # 修改语言

TIME_ZONE = 'Asia/Shanghai'    # 修改时区

启动开发服务器:

[root@localhost SimpleCMDB]$ python manage.py runserver 0.0.0.0:8000

Django SimpleCMDB 项目

定义数据模型:

[root@localhost SimpleCMDB]$ cat hostinfo/models.py
from django.db import models

# Create your models here.

class Host(models.Model):
    hostname = models.CharField(max_length=50)
    ip = models.IPAddressField()
    vendor = models.CharField(max_length=50)
    product = models.CharField(max_length=50)
    sn = models.CharField(max_length=50)
    cpu_model = models.CharField(max_length=50)
    cpu_num = models.IntegerField()
    memory = models.CharField(max_length=50)
    osver = models.CharField(max_length=50)

同步到数据库:

[root@localhost SimpleCMDB]$ python manage.py validate
[root@localhost SimpleCMDB]$ python manage.py syncdb

 
将数据模型注册到管理后台:

[root@localhost SimpleCMDB]$ cat hostinfo/admin.py
from django.contrib import admin
from hostinfo.models import Host

# Register your models here.

class HostAdmin(admin.ModelAdmin):
    list_display = [
        'hostname', 
        'ip',
        'cpu_model',
        'cpu_num',
        'memory',
        'vendor',
        'product',
        'osver',
        'sn',
    ]

admin.site.register(Host, HostAdmin)

Django SimpleCMDB 项目

通过 POST 方法收集主机信息到 SimpleCMDB:

[root@localhost SimpleCMDB]$ cat SimpleCMDB/urls.py
....
urlpatterns = patterns('',
    ....
    url(r'^hostinfo/collect/$', 'hostinfo.views.collect'),
)

[root@localhost SimpleCMDB]$ cat hostinfo/views.py 
from django.shortcuts import render
from django.http import HttpResponse
from hostinfo.models import Host

# Create your views here.

def collect(request):
    if request.POST:
        hostname = request.POST.get('hostname')
        ip = request.POST.get('ip')
        osver = request.POST.get('osver')
        vendor = request.POST.get('vendor')
        product = request.POST.get('product')
        cpu_model = request.POST.get('cpu_model')
        cpu_num = request.POST.get('cpu_num')
        memory = request.POST.get('memory')
        sn = request.POST.get('sn')
    
        host = Host()
        host.hostname = hostname
        host.ip = ip
        host.osver = osver
        host.vendor = vendor
        host.product = product
        host.cpu_model = cpu_model
        host.cpu_num = cpu_num
        host.memory = memory
        host.sn = sn
        host.save()

        return HttpResponse('OK')

    else:
        return HttpResponse('No Data!')

[root@localhost ~]$ cat /data/script/getHostInfo.py    
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import urllib, urllib2
from subprocess import Popen, PIPE

# 获取IP地址
def getIP():
    p = Popen('ifconfig', stdout=PIPE, shell=True)
    data = p.stdout.read().split('\n\n')
    for lines in data:
        if lines.startswith('lo'):
            continue
        if lines:
            ip = lines.split('\n')[1].split()[1].split(':')[1]
            break

    return ip


# 获取主机名
def getHostname():
    p = Popen('hostname', stdout=PIPE, shell=True)
    hostname = p.stdout.read().strip()
    return hostname


# 获取操作系统版本
def getOSVersion():
    with open('/etc/issue') as fd:
        data = fd.read().split('\n')[0]
        osVer = data.split()[0] + ' ' + data.split()[2]

    return osVer


# 获取服务器硬件信息
def getHardwareInfo(name):
    cmd = ''' dmidecode --type system | grep "%s" ''' % name
    p = Popen(cmd, stdout=PIPE, shell=True)
    hardwareInfo = p.stdout.read().split(':')[1].strip()
    return hardwareInfo


# 获取CPU型号
def getCPUModel():
    with open('/proc/cpuinfo') as fd:
        for line in fd.readlines():
            if line.startswith('model name'):
                cpuModel = line.split()[3].split('(')[0]
                break

    return cpuModel


# 获取CPU核数
def getCPUNum():
    with open('/proc/cpuinfo') as fd:
        for line in fd.readlines():
            if line.startswith('cpu cores'):
                cpuNum = line.split()[3]
                break

    return cpuNum


# 获取物理内存大小
def getMemorySize():
    with open('/proc/meminfo') as fd:
        memTotal = fd.readline().split()[1]

    memSize = str(int(memTotal)/1024) + 'M'
    return memSize


if __name__ == '__main__':
    hostInfo = {}
    hostInfo['ip'] = getIP()
    hostInfo['hostname'] = getHostname()
    hostInfo['osver'] = getOSVersion()
    hostInfo['vendor'] = getHardwareInfo('Manufacturer')
    hostInfo['product'] = getHardwareInfo('Product Name') 
    hostInfo['sn'] = getHardwareInfo('Serial Number')
    hostInfo['cpu_model'] = getCPUModel()
    hostInfo['cpu_num'] = getCPUNum()
    hostInfo['memory'] = getMemorySize()

    data = urllib.urlencode(hostInfo)    # 通过POST方法传递数据
    request = urllib2.urlopen('http://192.168.216.128:8000/hostinfo/collect/', data)
    print(request.read())

[root@localhost ~]$ python /data/script/getHostInfo.py    # 如果想收集其他主机信息,直接在其他主机跑这个脚本即可
OK

Django SimpleCMDB 项目

主机分组管理:

[root@localhost SimpleCMDB]$ cat hostinfo/models.py   # 创建模型,添加一张主机组的表
from django.db import models

....

class HostGroup(models.Model):
    group_name = models.CharField(max_length=50)      # 组名,使用的字段类型是CharField
    group_members = models.ManyToManyField(Host)      # 组成员,注意使用的字段及字段参数

[root@localhost SimpleCMDB]$ python manage.py validate
[root@localhost SimpleCMDB]$ python manage.py syncdb

[root@localhost SimpleCMDB]$ cat hostinfo/models.py    # 注册模型
from django.db import models

# Create your models here.

class Host(models.Model):
    hostname = models.CharField(max_length=50)
    ip = models.IPAddressField()
    vendor = models.CharField(max_length=50)
    product = models.CharField(max_length=50)
    sn = models.CharField(max_length=50)
    cpu_model = models.CharField(max_length=50)
    cpu_num = models.IntegerField()
    memory = models.CharField(max_length=50)
    osver = models.CharField(max_length=50)

    def __str__(self):
        return self.ip

class HostGroup(models.Model):
    group_name = models.CharField(max_length=50)
    group_members = models.ManyToManyField(Host)

Django SimpleCMDB 项目  

如下,当我们多次使用指定脚本收集主机信息时,如果数据库里有记录了,它还是会添加一条相同的记录:

Django SimpleCMDB 项目

因此我们需要修改一下视图函数,加个判断:

[root@localhost SimpleCMDB]$ cat hostinfo/views.py 
from django.shortcuts import render
from django.http import HttpResponse
from hostinfo.models import Host

# Create your views here.

def collect(request):
    if request.POST:
        hostname = request.POST.get('hostname')
        ip = request.POST.get('ip')
        osver = request.POST.get('osver')
        vendor = request.POST.get('vendor')
        product = request.POST.get('product')
        cpu_model = request.POST.get('cpu_model')
        cpu_num = request.POST.get('cpu_num')
        memory = request.POST.get('memory')
        sn = request.POST.get('sn')
    
        try:
            host = Host.objects.get(sn=sn)    # 查询数据库,查看是否有记录,如果有就重写记录,没有就添加记录
        except: 
            host = Host()    

        host.hostname = hostname
        host.ip = ip
        host.osver = osver
        host.vendor = vendor
        host.product = product
        host.cpu_model = cpu_model
        host.cpu_num = cpu_num
        host.memory = memory
        host.sn = sn
        host.save()

        return HttpResponse('OK')

    else:
        return HttpResponse('No Data!')
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
3年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Stella981 Stella981
3年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这