创建 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

定义数据模型:

[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)

通过 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

主机分组管理:

[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)

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

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

[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!')

Django SimpleCMDB 项目的更多相关文章

  1. Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 httplib模块 django和web服务器整合 wsgi模块 gunicorn模块

    Python第十三天   django 1.6   导入模板   定义数据模型   访问数据库   GET和POST方法    SimpleCMDB项目   urllib模块   urllib2模块 ...

  2. Django SimpleCMDB WSGI

    一.WSGI 介绍 (1) 在前面的学习中,我们是通过 python manage.py runserver 0.0.0.0:8000 来启动并访问开发服务器的:(2) 但在实际中我们是通过直接访问 ...

  3. django创建项目

    django创建项目 安装django pip install django==1.9 Note: C:\Python34\Scripts\pip.exe 创建项目 django-admin star ...

  4. Django练习项目之搭建博客

    背景:自从今年回家过年后,来到公司给我转了试用,我的学习效率感觉不如从前,而且刚步入社会我总是想要怎么想明白想清楚一些事,这通常会花掉,消耗我大量的精力,因为我想把我的生活管理规划好了,而在it技术学 ...

  5. Python Django CMDB项目实战之-3创建form表单,并在前端页面上展示

    基于之前的项目代码 Python Django CMDB项目实战之-1如何开启一个Django-并设置base页.index页.文章页面 Python Django CMDB项目实战之-2创建APP. ...

  6. Python Django CMDB项目实战之-2创建APP、建模(models.py)、数据库同步、高级URL、前端页面展示数据库中数据

    基于之前的项目代码来编写 Python Django CMDB项目实战之-1如何开启一个Django-并设置base页index页文章页面 现在我们修改一个文章列表是从数据库中获取数据, 下面我们就需 ...

  7. Python Django CMDB项目实战之-1如何开启一个Django-并设置base页、index页、文章页面

    1.环境 win10 python 2.7.14 django 1.8.2 需要用到的依赖包:MySQLdb(数据库的接口包).PIL/pillow(处理图片的包) 安装命令: pip install ...

  8. nginx + uwsgi 部署 Django+Vue项目

    nginx + uwsgi 部署 Django+Vue项目 windows 本地 DNS 解析 文件路径 C:\Windows\System32\drivers\etc 单机本地测试运行方式,调用dj ...

  9. Django商城项目笔记No.12用户部分-QQ登录2获取QQ用户openid

    Django商城项目笔记No.12用户部分-QQ登录2获取QQ用户openid 上一步获取QQ登录网址之后,测试登录之后本该跳转到这个界面 但是报错了: 新建oauth_callback.html & ...

随机推荐

  1. android尺子的自定义view——RulerView

    项目中用到自定义尺子的样式: 原代码在github上找的,地址:https://github.com/QQabby/HorizontalRuler 原效果为 因为跟自己要使用的view稍有不同  所以 ...

  2. ajax操作之操作 JavaScript 对象

    通过请求获取充分格式化的HTML虽然很方便,但这也意味着必须在传输文本内容的同时也 传输很多HTML标签.有时候,我们希望能够尽量少传输一些数据,然后马上处理这些数据.在 这种情况,我们希望取得能够通 ...

  3. [spark 快速大数据分析读书笔记] 第一章 导论

    [序言] Spark 基于内存的基本类型 (primitive)为一些应用程序带来了 100 倍的性能提升.Spark 允许用户程序将数据加载到 集群内存中用于反复查询,非常适用于大数据和机器学习. ...

  4. 输入一个int型整数,按照从右向左的阅读顺序,返回一个不含重复数字的新的整数。

    题目描述 输入一个int型整数,按照从右向左的阅读顺序,返回一个不含重复数字的新的整数. 输入描述: 输入一个int型整数 输出描述: 按照从右向左的阅读顺序,返回一个不含重复数字的新的整数 输入例子 ...

  5. Ubuntu18.04 + cuda9.0+cudnn7.0

    1 cannot find Toolkit in /usr/local/cuda-8.0 2017年05月27日 17:37:33 阅读数:2754  对于新版本ubuntukylin17.04安装C ...

  6. MyGUI 解析

    MyGUI源码还是比较简单的,我们在这里只是简单分析相应控件如何生成,如何渲染. 我们分成三个部分来说明,分别是资源类型,控件生成,控件渲染. 资源类型: ResourceSkin:用于记录各个控件状 ...

  7. DataFrame在算术方法中填充值

    在对不同索引的对象进行算术运算时, 你可能希望当一个对象中某个轴标签在另一个对象中找不到时填充一个特殊值(比如0)

  8. c语言数据类型、运算符和表达式

    数据类型 1.基本数据类型: 基本数据类型最主要的特点是,其值不可以分解为其他类型.也就是说,基本数据类型是 自我说明的 2.构造数据类型: 构造数据类型是根据已定于的一个或多个数据类型用构造的方法来 ...

  9. 多媒体开发之rtmp---rtmp client 端的实现

    去年我就在流媒体朋友圈认识winlin 老乡,本来想参与srs的开发,可惜今年5月份身体不好,今天想起rtmp 做直播,有翻到老乡的博文如下: http://blog.csdn.net/win_lin ...

  10. [转]iOS证书(.p12)和描述文件(.mobileprovision)申请

    转载于:http://ask.dcloud.net.cn/article/152 iOS有两种证书和描述文件: 证书类型 使用场景 开发(Development)证书和描述文件 用于开发测试,在HBu ...