Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Create a simplecmdb project

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Create a simplecmdb project

First, create a project simplecmdb, create an application, startapp hostinfo, and add an application to setting

[root@133] # cd / opt/python/django/ [root@133 django] # django-admin.py startproject simplecmdb [root@133 django] # cd simplecmdb/ [root@133 simplecmdb] # lsmanage.py simplecmdb [root@133 simplecmdb] # python manage.py startapp hostinfo [root@133 simplecmdb] # cd simplecmdb/ [root@133 simplecmdb] # vim settings.py# add app App: hostinfoINSTALLED_APPS = ('hostinfo',) # comment this line Allow the use of a third-party intermediate key MIDDLEWARE_CLASSES = (# 'django.middleware.csrf.CsrfViewMiddleware' ) # modify language coding and time zone LANGUAGE_CODE = 'zh-cn'TIME_ZONE =' Asia/Shanghai' [root@133 django] # cd / opt/python/django/simplecmdb/ [root@133 simplecmdb] # ll Total usage 12drwxr-xr-x 2 root root 4096 January 4 11:13 hostinfo-rwxr-xr-x 1 root root 253 January 4 11:12 manage.pydrwxr-xr-x 2 root root 4096 January 4 14:31 simplecmdb# launch server [root @ simplecmdb] # nohup python manage.py runserver 112.65.140.133 python manage.py runserver 112.65.140.133:8080Validating models...0 errors foundJanuary 8080 & [root@133 simplecmdb] # python manage.py runserver 112.65.140.133:8080Validating models...0 errors foundJanuary 04 2017-14:33:01Django version 1.6.5, using settings' simplecmdb.settings'Starting development server at http://112.65.140.133:8080/Quit the server with CONTROL-C.

Browsers access ok: http://11.65.140.13:8080/

Create a data model and define the data model in hostinfo

[root@133 simplecmdb] # cd / opt/python/django/simplecmdb/hostinfo/ [root@133 hostinfo] # ll Total usage 28 root root RW init__.py-rw-r--r-- r root root-1 root root 63 January 4 11:13 admin.py-rw-r--r-- 1 root root 194 January 4 14:33 admin.pyc-rw-r--r-- 1 root root 0 January 4 11:13 _ _ init__.py-rw-r--r-- 1 root root 137 January 4 14:33 _ _ init__.pyc-rw-r--r-- 1 root root 57 January 4 11:13 models.py-rw-r--r-- 1 root root 191 January 4 14:33 models.pyc-rw-r--r-- 1 root root 60 January 4 11:13 tests.py-rw-r--r-- 1 root root 63 January 4 11:13 views.py [root@133 hostinfo] # vim models.pyfrom 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 (max_length = 50) memory = models.CharField (max _ length= 50) osver = models.CharField (max_length = 50)

Initialize the data model, which saves the data model to the database

# check for errors [root@133 simplecmdb] # python manage.py validate0 errors found# View the sql [root@133 simplecmdb] # python manage.py sqlall hostinfoBEGIN that synchronization will perform CREATE TABLE "hostinfo_host" ("id" integer NOT NULL PRIMARY KEY, "hostname" varchar (50) NOT NULL, "ip" char (15) NOT NULL, "vendor" varchar (50) NOT NULL, "product" varchar (50) NOT NULL, "sn" varchar (50) NOT NULL, "cpu_model" varchar (50) NOT NULL, "cpu_num" integer NOT NULL, "memory" varchar (50) NOT NULL, "osver" varchar (50) NOT NULL); COMMIT # synchronize models to SQL [root @ 133sql] # python manage.py syncdbCreating tables... Creating table django_admin_logCreating table auth_permissionCreating table auth_group_permissionsCreating table auth_groupCreating table auth_user_groupsCreating table auth_user_user_permissionsCreating table auth_userCreating table django_content_typeCreating table django_sessionCreating table hostinfo_hostYou just installed Django's auth system, which means you don't have any superusers defined.Would you like to create one now? (yes/no): yesUsername (leave blank to use 'root'): root # user Email address: david-dai@zamplus.com # email Password: # enter password Password (again): Superuser created successfully.Installing custom SQL... Installing indexes... Installed 0 object (s) from 0 fixture (s)

Open the admin page and enter your user name and password to log in, but you can't see the host page

If you need to see the host page, you need to register host class, define the fields that need to be displayed in admin.py, and register in admin.site.register

[root@133 simplecmdb] # cd / opt/python/django/simplecmdb/hostinfo/ [root@133 hostinfo] # vim admin.pyfrom django.contrib import adminfrom hostinfo.models import Host # Import models.py under the hostinfo directory this module # Register your models here.# defines the fields to be displayed To display class HostAdmin (admin.ModelAdmin) on the web page: list_display = ['hostname',' ip', 'cpu_model',' cpu_num', 'memory',' vendor', 'product',' osver' 'sn'] admin.site.register (Host, HostAdmin)

After registering, I found that Host was displayed on the page

Click add host, add the configuration of host, and then click Save to display the relevant information.

Error record:

When defining the field in models.py, the vendor error was written as vender. As a result, the vendor field was not found and an error was reported when the later page went to the database to fetch data.

Solution:

1. Delete db.sqlite3

2. Modify models.py,vender to vendor, and reinitialize the sqlite3 database

Define the url access path (c in mvc, regular expression). When the user accesses the url of / hostinfo/collect, let the collect function in views in the hostinfo application handle

[root@133 simplecmdb] # vim urls.pyfrom django.conf.urls import patterns, include, urlfrom django.contrib import adminadmin.autodiscover () urlpatterns = patterns (', # Examples: # url (r'^ $', 'simplecmdb.views.home', name='home'), # url (r' ^ blog/', include ('blog.urls')), url (r' ^ admin/', include (admin.site.urls)), url (r'^ hostinfo/collect/$','hostinfo.views.collect') #)

4. Views.py defines the method of access

[root@133 simplecmdb] # vim / opt/python/django/simplecmdb/hostinfo/views.py from django.shortcuts import renderfrom django.http import HttpResponsefrom hostinfo.models import Host# Create your views here.def collect (req): if req.POST: hostname = req.POST.get ('hostname') ip = req.POST.get (' ip') osver = req.POST.get ('osver') vendor = req.POST.get (' vendor') ) product = req.POST.get ('product') cpu_model = req.POST.get (' cpu_model') cpu_num = req.POST.get ('cpu_num') memory = req.POST.get (' memory') sn = req.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') # use the curl method Pass the parameter, and use get to get the parameter [root@133 hostinfo] # curl-d hostname='node02'-d ip='192.168.1.2'-d osver='Centos6.5'-d vendor='HP'-d product='BL 380'-d sn='##$$123'-d cpu_model='Intel'-d cpu_num=16-d memory='32G' http://112.65.140.133:8080/hostinfo/collect/OK

1. Use shell to add hosts. In the shell script, there is a curl command. View the page, and the result shows that node03 has been added.

[root@133 django] # cd / opt/python/django/ [root@133 django] # vim data.sh curl-d hostname='node03'-d ip='192.168.1.3'-d osver='Centos6.5'-d vendor='HP'-d product='BL 380'-d sn='##$$123'-d cpu_model='Intel'-d cpu_num=16-d memory='32G' [root@133 django] # sh data.sh OK

2. Urllib,urllib2,httplib method transfers data under python to check the success of node04 transfer.

[root@133 django] # ipythonIn [4]: import urllib, urllib2In [5]: help (urllib2.urlopen) Help on function urlopen in module urllib2:urlopen (url, data=None, timeout=) In [7]: req = urllib2.urlopen ('http://112.65.140.133:8080/hostinfo/collect')In [8]: req.read () Out [8]:' no data' # return no data#'123' directly is not in the correct format Need to be in post format to In [12]: req = urllib2.urlopen ('http://112.65.140.133:8080/hostinfo/collect','123') File "", line 1 req = urllib2.urlopen (' http://112.65.140.133:8080/hostinfo/collect',) '123') ^ SyntaxError: invalid syntaxIn [13]: help (urllib.urlencode) Help on function urlencode in module urllib:urlencode (query, doseq=0) Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. In [16]: urllib.urlencode ({'hostname':'node05'}) Out [16]:' hostname=node05'In [18]: urllib.urlencode ({'hostname':'node05','ip':'192.168.1.5'}) Out [18]:' ip=192.168.1.5&hostname=node05'In [19]: dic = {'hostname':'node04','ip':'192.168.1.4','osver':'CentOS6.5','vendor':'david' 'p.: roduct':'BL 380th node04', david', cpu_model':'Intel','cpu_num':'16',' hostname': node04',' ip': '192.168.1.4' 'memory':' 16Gchains, 'osver':' CentOS6.5', 'product':' BL 380s, 'sn':' 12345'} In [20]: data = urllib.urlencode (dic) In [21]: dataOut [21]: 'product=BL+380&vendor=david&osver=CentOS6.5&sn=12345&memory=16G&cpu_num=16&ip=192.168.1.4&hostname=node04&cpu_model=Intel'In [12]: req = urllib2.urlopen (' http://112.65.140.133:8080/hostinfo/collect/',) Data) In [13]: req.read () Out [13]: 'OK'

3. Modify the python script and send the collected system information to the server directly.

[root@133 django] # cat sysinformation.py #! / usr/bin/env pythonimport urllib,urllib2 # Import urllib module from subprocess import Popen,PIPEdef getIfconfig (): P = Popen (['ifconfig'], stdout=PIPE) data = p.stdout.read () return datadef getDmi (): P = Popen ([' dmidecode']) Stdout = PIPE) data = p.stdout.read () return datadef parseData (data): parsed_data = [] new_line =''data = [i for i in data.split ('\ n') if I] for line in data: if line [0] .strip (): parsed_data.append (new_line) new_line = line +'\ n' else: New_line + = line +'\ n' parsed_data.append (new_line) return parsed_data def parseIfconfig (parsed_data): dic = {} tuple_addr= ('lo') 'vir','vnet','em3' 'em4') parsed_data = [i for i in parsed_data if i and not i.startswith (tuple_addr)] for lines in parsed_data: line_list = lines.split ('\ n') devname = line_list [0] .split () [0] macaddr = line_list [0] .split () [- 1] ipaddr = line_list [1] .split () [1] .split (': ') [1] break dic [' ip'] = devname Ipaddr Macaddr return dicdef parseDmi (parsed_data): dic = {} parsed_data = [i for i in parsed_data if i.startswith ('System Information')] parsed_data = [i for i in parsed_data [0] .split ('\ n') [1:] if I] dmi_dic = dict ([i.strip (). Split (':') for i in parsed_data]) dic ['vendor'] = dmi_dic [' Manufacturer'] .strip () dic ['product'] = dmi_dic [' Product Name'] .strip () dic ['sn'] = dmi_dic [' Serial Number'] .strip (f): with open (f) as fd: for line in fd: if line.startswith ('HOSTNAME'): hostname = line.split (' =') [1] .strip () Break return {'hostname':hostname} def getOSver (f): with open (f) as fd: for line in fd: osver = line.strip () break return {' osver':osver} def getCpu (f): num = 0 with open (f) as fd: for line in fd: if line.startswith ('processor'): Num + = 1 if line.startswith ('model name'): cpu_model = line.split (':') [1] .split () cpu_model = cpu_model [0] +'+ cpu_model [- 1] return {'cpu_num':num 'cpu_model':cpu_model} def getMemory (f): with open (f) as fd: for line in fd: if line.startswith (' MemTotal'): mem = int (line.split () [1] .strip ()) break mem = "% s"% int (mem/1024.0) +'M' return {'memory':mem} if _ _ Name__ = "_ main__": dic = {} data_ip = getIfconfig () parsed_data_ip = parseData (data_ip) ip = parseIfconfig (parsed_data_ip) data_dmi = getDmi () parsed_data_dmi = parseData (data_dmi) dmi = parseDmi (parsed_data_dmi) hostname = getHostname ('/ etc/sysconfig/network') osver = getOSver ('/ etc/issue') ) cpu = getCpu ('/ proc/cpuinfo') mem = getMemory ('/ proc/meminfo') dic.update (ip) dic.update (dmi) dic.update (hostname) dic.update (cpu) dic.update (mem) dic.update (osver) # convert the dictionary dic content to urlencode format Open the web page with urlopen and pass the data, and use req.read () to return the result d = urllib.urlencode (dic) req = urllib2.urlopen ('http://112.65.140.133:8080/hostinfo/collect/',d) print req.read () [root@133 django] # python sysinformation.py OK)

Viewing the web page, the real system information has been collected.

5. Group management of the collected host information

Create a HostGroup table, models.py

[root@133 simplecmdb] # cd / opt/python/django/simplecmdb/hostinfo/ [root@133 hostinfo] # ll Total usage 32 root root init__.py-rw-r--r---1 root root 405 January 4 15:38 admin.py-rw-r--r-- 1 root root 669 January 4 16:10 admin.pyc-rw-r--r-- 1 root root 0 11:13 _ _ init__.py-rw-r--r-- 1 January 137 January 4 14:33 _ _ init__.pyc-rw-r--r-- 1 root root 498 January 4 15:25 models.py-rw-r--r-- 1 root root 738 January 4 15:25 models.pyc-rw-r--r-- 1 root root 60 January 4 11:13 tests.py-rw-r--r-- 1 root root 1099 January 4 17:17 views.py-rw-r--r-- 1 root root 1115 January 4 17:17 views.pyc [root@133 hostinfo] # vim models.pyfrom 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 (max_length = 50) memory = models.CharField (max_length = 50) osver = models.CharField (max_length = 50) class HostGroup (models.Model): groupname = models.CharField (max_length = 50) members = models.ManyToManyField (Host) # synchronize database Created 2 tables [root@133 hostinfo] # cd.. [root@133 simplecmdb] # ll Total usage 60 nohup.outdrwxr-xr-x nohup.outdrwxr-xr-x-1 root root 35840 January 4 17:50 db.sqlite3drwxr-xr-x 2 root root 4096 January 4 20:10 hostinfo-rwxr-xr-x 1 root root 253 January 4 11:12 manage.py-rw- 1 root root 8640 January 4 16:59 nohup.outdrwxr-xr-x 2 root root 4096 1 Monthly 4 18:49 simplecmdb [root@133 simplecmdb] # python manage.py syncdbCreating tables... Creating table hostinfo_hostgroup_membersCreating table hostinfo_hostgroupInstalling custom SQL... Installing indexes... Installed 0 object (s) from 0 fixture (s) [root@133 simplecmdb] # ll Total usage 68 root 4 20:10 db.sqlite3drwxr-xr-x 2 root root 4096 January 4 20:10 hostinfo-rwxr-xr-x 1 root root 253 January 4 11:12 manage.py-rw- 1 root root 8640 January 4 16:59 nohup.outdrwxr-xr-x 2 root root 4096 January 4 18:49 simplecmdb [root@133 simplecmdb] # sqlite3 db.sqlite3 SQLite version 3.6.20Enter ".help" for instructionsEnter SQL statements terminated with a " "sqlite > .tablesauth _ group django_admin_log auth_group_permissions django_content_type auth_permission django_session auth_user hostinfo_host auth_user_groups hostinfo_hostgroup auth_user_user_permissions hostinfo_hostgroup_memberssqlite > .schema hostinfo_hostgroupCREATE TABLE" hostinfo_hostgroup "(" id "integer NOT NULL PRIMARY KEY "groupname" varchar (50) NOT NULL) Sqlite > .schema hostinfo_hostgroup_membersCREATE TABLE "hostinfo_hostgroup_members" ("id" integer NOT NULL PRIMARY KEY, "hostgroup_id" integer NOT NULL, "host_id" integer NOT NULL REFERENCES "hostinfo_host" ("id"), UNIQUE ("hostgroup_id", "host_id"); CREATE INDEX "hostinfo_hostgroup_members_27f00f5d" ON "hostinfo_hostgroup_members" ("host_id") CREATE INDEX "hostinfo_hostgroup_members_521bb4b0" ON "hostinfo_hostgroup_members" ("hostgroup_id"); sqlite > sqlite > .exit

Register database, admin.py

[root@133 hostinfo] # vim / opt/python/django/simplecmdb/hostinfo/admin.pyfrom django.contrib import adminfrom hostinfo.models import Host,HostGroup# Register your models here.class HostAdmin (admin.ModelAdmin): list_display = ['hostname',' ip', 'cpu_model',' cpu_num', 'memory',' vendor', 'product' Osver', 'sn'] class HostGroupAdmin (admin.ModelAdmin): list_display = [' groupname'] admin.site.register (Host, HostAdmin) admin.site.register (HostGroup,HostGroupAdmin)

You can see the Host groups group

If you need to display the hostname hostname when grouping, you need to inherit and override the self method in modles

[root@133 hostinfo] # vim / opt/python/django/simplecmdb/hostinfo/models.pyfrom 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 50) cpu_num = models.IntegerField (max_length = 50) memory = models.CharField (max_length = 50) osver = models.CharField (max_length = 50) # here specify the use of hostname to display def _ unicode__ (self): return self.hostnameclass HostGroup (models.Model): groupname = models.CharField (max_length = 50) members = models.ManyToManyField (Host)

Question: about def _ _ unicode__ (self): what is his function? yes, how does this return hostname relate to the following function HostGroup?

The host is associated with the host group through the field members = models.ManyToManyField (Host).

Def _ unicode__ (self) it serves the same purpose as overriding the _ _ str__ () method in a class. Let the class return a byte string, otherwise members displays the object.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report