博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python-Django收集主机信息
阅读量:6934 次
发布时间:2019-06-27

本文共 6662 字,大约阅读时间需要 22 分钟。

1.创建工程simplecmdb

django-admin.py startproject simplecmdb

2.创建应用

cd simplecmdb

python manage.py startapp hostinfo

3.编辑配置文件

vim simplecmdb/setting.py

1 INSTALLED_APPS = ( 2     'django.contrib.admin', 3     'django.contrib.auth', 4     'django.contrib.contenttypes', 5     'django.contrib.sessions', 6     'django.contrib.messages', 7     'django.contrib.staticfiles', 8     'hostinfo' 9 #添加应用10 )11 12 MIDDLEWARE_CLASSES = (13     'django.contrib.sessions.middleware.SessionMiddleware',14     'django.middleware.common.CommonMiddleware',15 #   'django.middleware.csrf.CsrfViewMiddleware',16 #注释csrf方便使用第三方工具curl17     'django.contrib.auth.middleware.AuthenticationMiddleware',18     'django.contrib.messages.middleware.MessageMiddleware',19     'django.middleware.clickjacking.XFrameOptionsMiddleware',20 )

4.添加model

1 from django.db import models 2  3 # Create your models here. 4  5 class Host(models.Model): 6     hostname = models.CharField(max_length=50) 7     ip = models.IPAddressField() 8     vendor = models.CharField(max_length=50) 9     product = models.CharField(max_length=50)10     sn = models.CharField(max_length=50)11     cpu_model = models.CharField(max_length=50)12     cpu_num = models.IntegerField()13     memory = models.CharField(max_length=50)14     osver = models.CharField(max_length=50)

5.初始化数据库

python manage.py sqlall hostinfo

python manage,py syncdb

6.编辑url.py,添加url

url(r'^hostinfo/collect/','hostinfo.views.collect')

7.编辑views.py

1 from django.shortcuts import render 2 from django.http import HttpResponse 3 from hostinfo.models import Host 4  5 # Create your views here. 6  7 def collect(req): 8     if req.POST: 9         hostname = req.POST.get('hostname')10         ip = req.POST.get('ip')11         product = req.POST.get('product')12         sn = req.POST.get('sn')13         vendor = req.POST.get('vendor')14         cpu_model = req.POST.get('cpu_model')15         cpu_num = req.POST.get('cpu_num')16         memory = req.POST.get('memory')17         osver = req.POST.get('osver')18 19         host = Host()20         host.hostname = hostname21         host.ip = ip22         host.product = product23         host.sn = sn24         host.vendor = vendor25         host.cpu_model = cpu_model26         host.cpu_num = cpu_num27         host.memory = memory28         host.osver = osver29 30         host.save()31 32         return HttpResponse('data have save into DB')33     else:34         return HttpResponse('there is no data from POST method')

8.注册model到admin界面

1 from django.contrib import admin 2 from hostinfo.models import Host 3  4 # Register your models here. 5  6 class HostAdmin(admin.ModelAdmin): 7     list_display = [ 8             'hostname', 9             'ip',10             'product',11             'vendor',12             'sn',13             'cpu_model',14             'cpu_num',15             'memory',16             'osver']17 18 admin.site.register(Host,HostAdmin)

9.启动服务

python manage.py runserver 0.0.0.0:8000

10.访问

curl -d hostname='node02' -d ip='192.168.1.2' -d product='BL 380' -d sn='XX213' -d vendor='HP' -d cpu_model='Intel' -d cpu_num=1 -d memory='250G' -d osver='md 05c' http://192.168.1.120:8000/hostinfo/collect/

1 #!/usr/bin/env python  2   3 import urllib,urllib2  4 from subprocess import Popen,PIPE  5   6 def getIfconfig():  7     p = Popen(['ifconfig'],stdout=PIPE)  8     data = p.stdout.read()  9     return data 10  11 def getDmi(): 12     p = Popen(['dmidecode'],stdout=PIPE) 13     data = p.stdout.read() 14     return data 15  16 def parseData(data): 17     parsed_data = [] 18     new_line = '' 19     data = [i for i in data.split('\n') if i] 20     for line in data: 21         if line[0].strip(): 22              parsed_data.append(new_line) 23             new_line = line +'\n' 24         else:         25             new_line += line+'\n' 26     parsed_data.append(new_line) 27     return [i for i in parsed_data if i] 28  29 def parseIfconfig(parsed_data): 30     parsed_data = [i for i in parsed_data if not i.startswith('lo')] 31     for lines in parsed_data: 32         line_list = lines.split('\n') 33         devname = line_list[0].split()[0] 34         macaddr = line_list[0].split()[-1] 35         ipaddr = line_list[1].split()[1].split(':')[1] 36         break 37     dic['ip'] =ipaddr 38     return dic 39  40 def parseDmi(parsed_data): 41     dic = {} 42     parsed_data = [i for i in parsed_data if i.startswith('System Information')] 43     parsed_data = [i for i in parsed_data[0].split('\n')[1:] if i] 44     dmi_dic =  dict([i.strip().split(':') for i in parsed_data]) 45     dic['vendor'] = dmi_dic['Manufacturer'].strip() 46     dic['product'] = dmi_dic['Product Name'].strip() 47     dic['sn'] = dmi_dic['Serial Number'].strip()[:15] 48     return dic 49  50 def getHostname(f): 51     with open(f) as fd: 52         for line in fd: 53             if line.startswith('HOSTNAME'): 54                 hostname = line.split('=')[1].strip() 55                 break 56     return {
'hostname':hostname} 57 58 def getOsver(f): 59 with open(f) as fd: 60 for line in fd: 61 osver = line.strip() 62 break 63 return {
'osver':osver} 64 65 def getCpu(f): 66 num = 0 67 with open(f) as fd: 68 for line in fd: 69 if line.startswith('processor'): 70 num +=1 71 if line.startswith('model name'): 72 cpu_model = line.split(':')[1].split() 73 cpu_model = cpu_model[0]+' '+cpu_model[-1] 74 return {
'cpu_num':num,'cpu_model':cpu_model} 75 76 def getMemory(f): 77 with open(f) as fd: 78 for line in fd: 79 if line.startswith('MemTotal'): 80 mem = int(line.split()[1].strip()) 81 break 82 mem = "%d" % int(mem/1024.0)+'M' 83 return {
'memory':mem} 84 85 86 if __name__ == '__main__': 87 dic = {} 88 data_ip = getIfconfig() 89 parsed_data_ip = parseData(data_ip) 90 ip = parseIfconfig(parsed_data_ip) 91 data_dmi = getDmi() 92 parsed_data_dmi = parseData(data_dmi) 93 dmi = parseDmi(parsed_data_dmi) 94 hostname = getHostname('/etc/sysconfig/network') 95 osver = getOsver('/etc/issue') 96 cpu = getCpu('/proc/cpuinfo') 97 mem = getMemory('/proc/meminfo') 98 dic.update(ip) 99 dic.update(dmi)100 dic.update(hostname)101 dic.update(osver)102 dic.update(cpu)103 dic.update(mem)104 data = urllib.urlencode(dic)105 req = urllib2.urlopen('http://192.168.1.120:8000/hostinfo/collect/',data)106 print req.read()

 

转载于:https://www.cnblogs.com/Nyan-Workflow-FC/p/5699347.html

你可能感兴趣的文章
如何在Azure环境里做好信息传递可扩展性经验分享
查看>>
2016-6-6
查看>>
vuex 使用
查看>>
java第三周作业
查看>>
回调函数
查看>>
ASCII 码表
查看>>
25个出众的Web表单范例
查看>>
mysql sql语句大全
查看>>
Invoke 和 BeginInvoke 的区别
查看>>
linux系统编程之进程(四):进程退出exit,_exit区别即atexit函数(转载)
查看>>
钉子和小球
查看>>
正则匹配之——引擎匹配原理
查看>>
实现文件上传的多种方法
查看>>
Windows Phone 7 开发常见问题汇总
查看>>
$$ kcptun lede koolshare 科学 油管
查看>>
页面loading效果
查看>>
python sort、sorted
查看>>
openERP笔记,自定义开发模块
查看>>
Java Remote Debug(idea远程调试)
查看>>
使用OAuth2的SSO分析
查看>>