├── .gitignore
├── README.md
├── cmdb.py
├── cmdb
├── cmdb
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3
├── main
│ ├── __init__.py
│ ├── admin.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0002_auto_20150903_0148.py
│ │ ├── 0003_auto_20150903_0918.py
│ │ ├── 0004_search.py
│ │ ├── 0005_auto_20150905_1427.py
│ │ ├── 0006_os.py
│ │ ├── 0007_host_os.py
│ │ ├── 0008_auto_20150907_0643.py
│ │ ├── 0009_auto_20150907_0657.py
│ │ ├── 0010_auto_20150907_0704.py
│ │ ├── 0011_auto_20150907_0733.py
│ │ ├── 0012_auto_20150907_0751.py
│ │ ├── 0013_auto_20151025_0007.py
│ │ └── __init__.py
│ ├── models.py
│ ├── templates
│ │ ├── list.html
│ │ └── search.html
│ ├── tests.py
│ └── views.py
└── manage.py
└── ecs.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # cmdb
2 |
3 | 运行之前先配置accesskeyid,accesskeysecret
4 |
5 | ```
6 | python ecs.py config --id=[accesskeyid] --secret=[accesskeysecret]
7 | ```
8 |
9 | 配置正确的话运行
10 | python ecs.py DescribeRegions
11 | 会得到
12 |
13 | ```
14 | {
15 | "Regions": {
16 | "Region": [
17 | {
18 | "LocalName": "\u6df1\u5733",
19 | "RegionId": "cn-shenzhen"
20 | },
21 | {
22 | "LocalName": "\u9752\u5c9b",
23 | "RegionId": "cn-qingdao"
24 | },
25 | {
26 | "LocalName": "\u5317\u4eac",
27 | "RegionId": "cn-beijing"
28 | },
29 | {
30 | "LocalName": "\u9999\u6e2f",
31 | "RegionId": "cn-hongkong"
32 | },
33 | {
34 | "LocalName": "\u676d\u5dde",
35 | "RegionId": "cn-hangzhou"
36 | },
37 | {
38 | "LocalName": "\u7f8e\u56fd\u7845\u8c37",
39 | "RegionId": "us-west-1"
40 | }
41 | ]
42 | },
43 | "RequestId": "8C3B760F-D126-413E-A67D-D3E81C3E1CBF"
44 | }
45 | ```
46 |
47 | 之后我又重写了一个django的项目,不单是界面了,重写了很多代码。
48 |
--------------------------------------------------------------------------------
/cmdb.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import json
3 | #from xlwt import Workbook
4 | import xlwt
5 | import datetime
6 |
7 |
8 | # ecs.py DescribeRegions
9 | #global vars
10 | ecsfile = '/Users/aca/github/cmdb/ecs.py'
11 | regs=[]
12 | #ecs arrays
13 | arr_ecs = []
14 |
15 |
16 |
17 | class timelog:
18 | # start_time = datetime.now()
19 |
20 | def __init__(self):
21 | self.start_time = datetime.datetime.now()
22 | print "Timer plugin is active."
23 | def end(self):
24 | self.end_time = datetime.datetime.now()
25 | def p(self):
26 | print "past %d seconds\n" % ((self.end_time - self.start_time).seconds)
27 | print "past %d microseconds\n" % ((self.end_time - self.start_time).microseconds)
28 |
29 |
30 | def get_regions():
31 | child1 = subprocess.Popen(["python",ecsfile,"DescribeRegions"],stdout=subprocess.PIPE)
32 | #child1 = subprocess.Popen(["python","/Users/aca/cmdb/ecs.py DescribeRegions"],stdout=subprocess.PIPE)
33 | res = child1.communicate()
34 | #print res[0]
35 | #print type(res[0])
36 |
37 | j = json.loads(res[0])
38 |
39 | #print type(j)
40 | arr = j["Regions"]["Region"]
41 | #print type(arr)
42 | for i in arr:
43 | # print i["LocalName"],i["RegionId"]
44 | regs.append(i["RegionId"])
45 | #print arr[i]["LocalName"]
46 | get_regions()
47 | print regs
48 |
49 | class c_ecs:
50 | InstanceId=''
51 | InnerIpAddress=''
52 | PublicIpAddress=''
53 | ImageId=''
54 | Status = ''
55 | ZoneId = ''
56 | InstanceType = ''
57 | InstanceName = ''
58 | def p(self):
59 | print ("InstanceId=%s \n InnerIpAddress=%s \n PublicIpAddress=%s \n ImageId=%s \n Status=%s \n ZoneId=%s \n InstanceType=%s \n InstanceName=%s \n" %(self.InstanceId,self.InnerIpAddress,self.PublicIpAddress,self.ImageId,self.Status,self.ZoneId ,self.InstanceType ,self.InstanceName))
60 |
61 |
62 |
63 | def get_ecs( reg ):
64 | # RegionID=cn-hangzhou
65 | str_reg="RegionID="+reg
66 | # print str_reg
67 | clild1 = subprocess.Popen(["python",ecsfile,"DescribeInstances",str_reg],stdout=subprocess.PIPE)
68 | res = clild1.communicate()
69 | j = json.loads(res[0])
70 |
71 | arr = j["Instances"]["Instance"]
72 |
73 | for i in arr:
74 | # print i["InstanceId"],i["InnerIpAddress"]["IpAddress"][0],i["PublicIpAddress"]["IpAddress"][0],i["ImageId"]
75 | e = c_ecs()
76 | e.InstanceId = i["InstanceId"]
77 | e.InnerIpAddress = i["InnerIpAddress"]["IpAddress"][0]
78 | e.PublicIpAddress = i["PublicIpAddress"]["IpAddress"][0]
79 | e.ImageId = i["ImageId"]
80 | e.Status = i["Status"]
81 | e.ZoneId = i["ZoneId"]
82 | e.InstanceType = i["InstanceType"]
83 | e.InstanceName = i["InstanceName"]
84 | arr_ecs.append(e)
85 | # return e
86 |
87 | def save_to_file( filename ):
88 | wb = xlwt.Workbook()
89 | for i in regs:
90 | get_ecs(i)
91 | #wb.add_sheet(i)
92 | # e = c_ecs()
93 | # e = get_ecs(i)
94 | # e.p()
95 |
96 | ws = wb.add_sheet('ecs')
97 | ws.write(0,0,'InstanceId')
98 | ws.write(0,1,'InnerIpAddress')
99 | ws.write(0,2,'PublicIpAddress')
100 | ws.write(0,3,'ImageId')
101 | ws.write(0,4,'Status')
102 | ws.write(0,5,'ZoneId')
103 | ws.write(0,6,'InstanceType')
104 | ws.write(0,7,'InstanceName')
105 | j = 1
106 | for i in arr_ecs:
107 | i.p()
108 | ws.write(j,0,i.InstanceId)
109 | ws.write(j,1,i.InnerIpAddress)
110 | ws.write(j,2,i.PublicIpAddress)
111 | ws.write(j,3,i.ImageId)
112 | ws.write(j,4,i.Status)
113 | ws.write(j,5,i.ZoneId)
114 | ws.write(j,6,i.InstanceType)
115 | ws.write(j,7,i.InstanceName)
116 | j = j+1
117 |
118 | #wb.save('ecs.xls')
119 | wb.save( filename )
120 | # book.add_sheet(i)
121 |
122 | def main():
123 | tl = timelog()
124 | save_to_file('ecs.xls')
125 | tl.end()
126 | tl.p()
127 |
128 | main()
129 | #for i in regs:
130 | # sheet1 = book.add_sheet(i)
131 |
132 |
133 |
134 |
135 |
136 |
--------------------------------------------------------------------------------
/cmdb/cmdb/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gqdw/cmdb/f09f7bd8c2af51129471f8157e9126c54ca7d8b9/cmdb/cmdb/__init__.py
--------------------------------------------------------------------------------
/cmdb/cmdb/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for cmdb project.
3 |
4 | Generated by 'django-admin startproject' using Django 1.8.3.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/1.8/topics/settings/
8 |
9 | For the full list of settings and their values, see
10 | https://docs.djangoproject.com/en/1.8/ref/settings/
11 | """
12 |
13 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
14 | import os
15 |
16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17 |
18 |
19 | # Quick-start development settings - unsuitable for production
20 | # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
21 |
22 | # SECURITY WARNING: keep the secret key used in production secret!
23 | SECRET_KEY = 'o$dnpg(-tju(e$3qy6v8#r2+lnl=vz5=&bm$nvhc8nyc=8#nry'
24 |
25 | # SECURITY WARNING: don't run with debug turned on in production!
26 | DEBUG = True
27 |
28 | ALLOWED_HOSTS = []
29 |
30 |
31 | # Application definition
32 |
33 | INSTALLED_APPS = (
34 | 'django.contrib.admin',
35 | 'django.contrib.auth',
36 | 'django.contrib.contenttypes',
37 | 'django.contrib.sessions',
38 | 'django.contrib.messages',
39 | 'django.contrib.staticfiles',
40 | 'main',
41 | 'bootstrap3',
42 | )
43 |
44 | MIDDLEWARE_CLASSES = (
45 | 'django.contrib.sessions.middleware.SessionMiddleware',
46 | 'django.middleware.common.CommonMiddleware',
47 | 'django.middleware.csrf.CsrfViewMiddleware',
48 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
49 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
50 | 'django.contrib.messages.middleware.MessageMiddleware',
51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
52 | 'django.middleware.security.SecurityMiddleware',
53 | )
54 |
55 | ROOT_URLCONF = 'cmdb.urls'
56 |
57 | TEMPLATES = [
58 | {
59 | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 | 'DIRS': [],
61 | 'APP_DIRS': True,
62 | 'OPTIONS': {
63 | 'context_processors': [
64 | 'django.template.context_processors.debug',
65 | 'django.template.context_processors.request',
66 | 'django.contrib.auth.context_processors.auth',
67 | 'django.contrib.messages.context_processors.messages',
68 | ],
69 | },
70 | },
71 | ]
72 |
73 | WSGI_APPLICATION = 'cmdb.wsgi.application'
74 |
75 |
76 | # Database
77 | # https://docs.djangoproject.com/en/1.8/ref/settings/#databases
78 |
79 | DATABASES = {
80 | 'default': {
81 | 'ENGINE': 'django.db.backends.sqlite3',
82 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
83 | }
84 | }
85 |
86 |
87 | # Internationalization
88 | # https://docs.djangoproject.com/en/1.8/topics/i18n/
89 |
90 | LANGUAGE_CODE = 'en-us'
91 |
92 | TIME_ZONE = 'UTC'
93 |
94 | USE_I18N = True
95 |
96 | USE_L10N = True
97 |
98 | USE_TZ = True
99 |
100 |
101 | # Static files (CSS, JavaScript, Images)
102 | # https://docs.djangoproject.com/en/1.8/howto/static-files/
103 |
104 | STATIC_URL = '/static/'
105 |
--------------------------------------------------------------------------------
/cmdb/cmdb/urls.py:
--------------------------------------------------------------------------------
1 | """cmdb URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/1.8/topics/http/urls/
5 | Examples:
6 | Function views
7 | 1. Add an import: from my_app import views
8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
9 | Class-based views
10 | 1. Add an import: from other_app.views import Home
11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
12 | Including another URLconf
13 | 1. Add an import: from blog import urls as blog_urls
14 | 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
15 | """
16 | from django.conf.urls import include, url
17 | from django.contrib import admin
18 |
19 | urlpatterns = [
20 | url(r'^admin/', include(admin.site.urls)),
21 | url(r'^search/$','main.views.search'),
22 | url(r'^list/$','main.views.listhost'),
23 | url(r'^$','main.views.search'),
24 | url(r'^addhost/','main.views.addhost'),
25 | ]
26 |
--------------------------------------------------------------------------------
/cmdb/cmdb/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for cmdb project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.wsgi import get_wsgi_application
13 |
14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cmdb.settings")
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/cmdb/db.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gqdw/cmdb/f09f7bd8c2af51129471f8157e9126c54ca7d8b9/cmdb/db.sqlite3
--------------------------------------------------------------------------------
/cmdb/main/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gqdw/cmdb/f09f7bd8c2af51129471f8157e9126c54ca7d8b9/cmdb/main/__init__.py
--------------------------------------------------------------------------------
/cmdb/main/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 | from .models import Hostgroup,Host,Region,Search,Os,Dbtype,Rds
3 |
4 | # Register your models here.
5 | class HostAdmin(admin.ModelAdmin):
6 | list_display = ('hostname','eth0','eth1','group','os')
7 | #search_fields= ['group']
8 | search_fields= ['hostname','eth0']
9 | #search_fields= ('hostname','eth0','eth1','group')
10 | list_field = ('group',)
11 | # filter_horizontal = ('Region',)
12 |
13 | admin.site.register(Hostgroup)
14 | #admin.site.register(Host)
15 | admin.site.register(Host,HostAdmin)
16 | admin.site.register(Region)
17 | admin.site.register(Rds)
18 | admin.site.register(Dbtype)
19 | #admin.site.register(Search)
20 | admin.site.register(Os)
21 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ]
11 |
12 | operations = [
13 | migrations.CreateModel(
14 | name='Host',
15 | fields=[
16 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
17 | ('hostname', models.CharField(max_length=30)),
18 | ('eth0', models.GenericIPAddressField()),
19 | ('eth1', models.GenericIPAddressField()),
20 | ('beizhu', models.TextField()),
21 | ('Region', models.CharField(max_length=3, choices=[(b'hz', b'cn-hangzhou'), (b'ss', b'cn-shenzhen'), (b'qd', b'cn-qingdao'), (b'bj', b'cn-beijing'), (b'sh', b'cn-shanghai'), (b'hk', b'cn-hongkong'), (b'us1', b'us-west-1')])),
22 | ('test', models.TextField()),
23 | ('test2', models.TextField()),
24 | ],
25 | ),
26 | migrations.CreateModel(
27 | name='Hostgroup',
28 | fields=[
29 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
30 | ('groupname', models.CharField(max_length=30)),
31 | ],
32 | ),
33 | migrations.AddField(
34 | model_name='host',
35 | name='group',
36 | field=models.ForeignKey(to='main.Hostgroup'),
37 | ),
38 | ]
39 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0002_auto_20150903_0148.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0001_initial'),
11 | ]
12 |
13 | operations = [
14 | migrations.CreateModel(
15 | name='Region',
16 | fields=[
17 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
18 | ('regionname', models.CharField(max_length=30)),
19 | ],
20 | ),
21 | migrations.RemoveField(
22 | model_name='host',
23 | name='test',
24 | ),
25 | migrations.RemoveField(
26 | model_name='host',
27 | name='test2',
28 | ),
29 | migrations.AlterField(
30 | model_name='host',
31 | name='Region',
32 | field=models.ForeignKey(to='main.Region'),
33 | ),
34 | ]
35 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0003_auto_20150903_0918.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0002_auto_20150903_0148'),
11 | ]
12 |
13 | operations = [
14 | migrations.AlterField(
15 | model_name='host',
16 | name='beizhu',
17 | field=models.TextField(blank=True),
18 | ),
19 | ]
20 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0004_search.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0003_auto_20150903_0918'),
11 | ]
12 |
13 | operations = [
14 | migrations.CreateModel(
15 | name='Search',
16 | fields=[
17 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
18 | ('times', models.IntegerField()),
19 | ],
20 | ),
21 | ]
22 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0005_auto_20150905_1427.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0004_search'),
11 | ]
12 |
13 | operations = [
14 | migrations.AlterField(
15 | model_name='host',
16 | name='eth0',
17 | field=models.GenericIPAddressField(unique=True),
18 | ),
19 | migrations.AlterField(
20 | model_name='host',
21 | name='eth1',
22 | field=models.GenericIPAddressField(null=True, blank=True),
23 | ),
24 | migrations.AlterField(
25 | model_name='host',
26 | name='hostname',
27 | field=models.CharField(unique=True, max_length=30),
28 | ),
29 | ]
30 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0006_os.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0005_auto_20150905_1427'),
11 | ]
12 |
13 | operations = [
14 | migrations.CreateModel(
15 | name='Os',
16 | fields=[
17 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
18 | ('osname', models.CharField(default=b'Centos6', max_length=10, blank=True)),
19 | ],
20 | ),
21 | ]
22 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0007_host_os.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0006_os'),
11 | ]
12 |
13 | operations = [
14 | migrations.AddField(
15 | model_name='host',
16 | name='os',
17 | field=models.ForeignKey(default=1, to='main.Os'),
18 | preserve_default=False,
19 | ),
20 | ]
21 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0008_auto_20150907_0643.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0007_host_os'),
11 | ]
12 |
13 | operations = [
14 | migrations.CreateModel(
15 | name='Dbtype',
16 | fields=[
17 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
18 | ('mem', models.CharField(unique=True, max_length=20)),
19 | ('connections', models.IntegerField()),
20 | ('iops', models.IntegerField()),
21 | ],
22 | ),
23 | migrations.CreateModel(
24 | name='Rds',
25 | fields=[
26 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
27 | ('dns', models.URLField(max_length=50)),
28 | ],
29 | ),
30 | migrations.AlterField(
31 | model_name='host',
32 | name='Region',
33 | field=models.ForeignKey(default=6, to='main.Region'),
34 | ),
35 | migrations.AlterField(
36 | model_name='host',
37 | name='os',
38 | field=models.ForeignKey(default=1, to='main.Os'),
39 | ),
40 | migrations.AlterField(
41 | model_name='region',
42 | name='regionname',
43 | field=models.CharField(default=b'cn-hangzhou', max_length=30),
44 | ),
45 | migrations.AddField(
46 | model_name='rds',
47 | name='Region',
48 | field=models.ForeignKey(default=6, to='main.Region'),
49 | ),
50 | migrations.AddField(
51 | model_name='rds',
52 | name='dbtype',
53 | field=models.ForeignKey(to='main.Dbtype'),
54 | ),
55 | migrations.AddField(
56 | model_name='rds',
57 | name='group',
58 | field=models.ForeignKey(to='main.Hostgroup'),
59 | ),
60 | ]
61 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0009_auto_20150907_0657.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0008_auto_20150907_0643'),
11 | ]
12 |
13 | operations = [
14 | migrations.AlterField(
15 | model_name='dbtype',
16 | name='connections',
17 | field=models.IntegerField(unique=True),
18 | ),
19 | migrations.AlterField(
20 | model_name='dbtype',
21 | name='iops',
22 | field=models.IntegerField(unique=True),
23 | ),
24 | ]
25 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0010_auto_20150907_0704.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0009_auto_20150907_0657'),
11 | ]
12 |
13 | operations = [
14 | migrations.AlterField(
15 | model_name='dbtype',
16 | name='mem',
17 | field=models.IntegerField(unique=True),
18 | ),
19 | ]
20 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0011_auto_20150907_0733.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0010_auto_20150907_0704'),
11 | ]
12 |
13 | operations = [
14 | migrations.AlterField(
15 | model_name='dbtype',
16 | name='connections',
17 | field=models.IntegerField(),
18 | ),
19 | migrations.AlterField(
20 | model_name='dbtype',
21 | name='iops',
22 | field=models.IntegerField(),
23 | ),
24 | ]
25 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0012_auto_20150907_0751.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0011_auto_20150907_0733'),
11 | ]
12 |
13 | operations = [
14 | migrations.AlterField(
15 | model_name='rds',
16 | name='dns',
17 | field=models.CharField(max_length=50),
18 | ),
19 | ]
20 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/0013_auto_20151025_0007.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('main', '0012_auto_20150907_0751'),
11 | ]
12 |
13 | operations = [
14 | migrations.AlterField(
15 | model_name='os',
16 | name='osname',
17 | field=models.CharField(default=b'Centos6', unique=True, max_length=10, blank=True),
18 | ),
19 | ]
20 |
--------------------------------------------------------------------------------
/cmdb/main/migrations/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gqdw/cmdb/f09f7bd8c2af51129471f8157e9126c54ca7d8b9/cmdb/main/migrations/__init__.py
--------------------------------------------------------------------------------
/cmdb/main/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 | # Create your models here.
4 |
5 |
6 | class Hostgroup(models.Model):
7 | groupname = models.CharField(max_length=30)
8 |
9 | def __unicode__(self):
10 | return self.groupname
11 |
12 |
13 | class Region(models.Model):
14 | regionname = models.CharField(max_length=30, default='cn-hangzhou')
15 |
16 | def __unicode__(self):
17 | return self.regionname
18 |
19 |
20 | class Search(models.Model):
21 | times = models.IntegerField()
22 |
23 | def __unicode__(self):
24 | return str(self.times)
25 |
26 | def add(self):
27 | self.times += 1
28 | self.save()
29 |
30 |
31 | class OsManager(models.Manager):
32 |
33 | def create_os(self, name):
34 | os = self.create(osname=name)
35 | return os
36 |
37 |
38 | class Os(models.Model):
39 | osname = models.CharField(max_length=10, default='Centos6', blank=True, unique=True)
40 |
41 | def __unicode__(self):
42 | return self.osname
43 |
44 | objects = OsManager()
45 | #@classmethod
46 | #def create(cls,name):
47 | # os = cls(osname=name)
48 | # return os
49 |
50 |
51 | class Dbtype(models.Model):
52 | # dbname = models.CharField(max_length=20,unique=True)
53 |
54 | def setval(self,mem,con,iops):
55 | self.mem = mem
56 | self.connections = con
57 | self.iops = iops
58 | mem = models.IntegerField(unique=True)
59 | connections = models.IntegerField()
60 | iops = models.IntegerField()
61 |
62 | def __unicode__(self):
63 | return "%sMB %i %i" % (self.mem, self.connections, self.iops)
64 |
65 |
66 | class Rds(models.Model):
67 | group = models.ForeignKey(Hostgroup)
68 | dns = models.CharField(max_length=50)
69 | dbtype = models.ForeignKey(Dbtype)
70 |
71 | def __unicode__(self):
72 | return "%s %s" % (self.dns,self.dbtype)
73 | #type ,mem,connections,iops
74 |
75 | Region = models.ForeignKey(Region,default=6)
76 |
77 |
78 | class Host(models.Model):
79 | CRegions = (
80 | ('hz','cn-hangzhou'),
81 | ('ss','cn-shenzhen'),
82 | ('qd','cn-qingdao'),
83 | ('bj','cn-beijing'),
84 | ('sh','cn-shanghai'),
85 | ('hk','cn-hongkong'),
86 | ('us1','us-west-1'),
87 | )
88 | group = models.ForeignKey(Hostgroup)
89 | os = models.ForeignKey(Os, default=1)
90 | hostname = models.CharField(max_length=30, unique=True)
91 | eth0 = models.GenericIPAddressField(unique=True)
92 | eth1 = models.GenericIPAddressField(blank=True, null=True )
93 | beizhu = models.TextField(blank=True)
94 | # Region = models.CharField(max_length=3,choices=CRegions)
95 | Region = models.ForeignKey(Region, default=6)
96 | # test = models.TextField()
97 | # test2 = models.TextField()
98 |
99 | def __unicode__(self):
100 | return '%s %s %s %s' % (self.hostname, self.eth0, self.eth1, self.group)
101 | # RegionID =
102 | # os =
103 | # cpu =
104 | # memory =
105 |
--------------------------------------------------------------------------------
/cmdb/main/templates/list.html:
--------------------------------------------------------------------------------
1 | {# Load the tag library #}
2 | {% load bootstrap3 %}
3 |
4 | {# Load CSS and JavaScript #}
5 | {% bootstrap_css %}
6 | {% bootstrap_javascript %}
7 |
8 | {# Display django.contrib.messages as Bootstrap alerts #}
9 | {% bootstrap_messages %}
10 |
11 |
12 |
13 |
14 |
Rds Lists
15 |
16 | {% for host in hosts %}
17 |
18 | {{ host.hostname }} |
19 | {{ host.eth0 }} |
20 | {{ host.eth1 }} |
21 | {{ host.group }} |
22 |
23 | {% endfor %}
24 |
25 |
26 |
27 |
28 |
29 |
Rds Lists
30 |
31 | {% for rds in rdss %}
32 |
33 | {{rds.dns}} |
34 | {{rds.dbtype.mem}}MB |
35 | {{rds.dbtype.connections}} |
36 | {{rds.dbtype.iops}} |
37 | {{rds.group}} |
38 |
39 |
40 | {% endfor %}
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/cmdb/main/templates/search.html:
--------------------------------------------------------------------------------
1 | {# Load the tag library #}
2 | {% load bootstrap3 %}
3 |
4 | {# Load CSS and JavaScript #}
5 | {% bootstrap_css %}
6 | {% bootstrap_javascript %}
7 |
8 | {# Display django.contrib.messages as Bootstrap alerts #}
9 | {% bootstrap_messages %}
10 |
11 |
12 | search
13 | {% if form.errors %}
14 |
15 | Please correct the error{{ form.errors|pluralize }} below.
16 |
17 | {% endif %}
18 |
19 |
32 |
33 |
34 | {% if hosts %}
35 |
36 | hostname |
37 | eth0 |
38 | eth1 |
39 | Group |
40 |
41 | {% endif %}
42 | {% for host in hosts %}
43 |
44 | {{ host.hostname }} |
45 | {{ host.eth0 }} |
46 | {{ host.eth1 }} |
47 | {{ host.group }} |
48 |
49 | {% endfor %}
50 |
51 | {% if times %}
52 | 第{{ times }}次搜索
53 | {% endif %}
54 |
55 |
--------------------------------------------------------------------------------
/cmdb/main/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/cmdb/main/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render
2 | from django.http import HttpResponse
3 | from django import forms
4 | from .models import Host,Search,Hostgroup,Rds
5 | # Create your views here.
6 |
7 | class Searchbox(forms.Form):
8 | host = forms.CharField(max_length=30)
9 |
10 | def search( request ):
11 | # hosts = Host.objects.all()
12 | if request.method == 'POST':
13 | form = Searchbox(request.POST)
14 | if form.is_valid():
15 | cd = form.cleaned_data
16 | print cd['host']
17 | hosts = Host.objects.filter(hostname__contains=cd['host'] )
18 | s = Search.objects.get()
19 | s.add()
20 | # s.times += 1
21 | # s.save()
22 |
23 | #hosts = Host.objects.get(hostname__iexact = cd['host'] )
24 | print hosts
25 | # host_list = []
26 | # for h in hosts:
27 | # print h.hostname.find(cd['host'])
28 | # if h.hostname.find(cd['host']) != -1:
29 | # #if h.hostname == cd['host']:
30 | # host_list.append(h)
31 |
32 | # return HttpResponse('ok')
33 | return render( request,'search.html',{ 'form':form ,'hosts':hosts,'times':s.times})
34 | #return render( request,'search.html',{ 'form':form ,'hosts':host_list})
35 | else:
36 | form = Searchbox()
37 | return render( request,'search.html',{ 'form':form })
38 |
39 | def listhost( request ):
40 | hosts = Host.objects.all()
41 | # groups = Hostgroup.objects.all()
42 | rdss= Rds.objects.all()
43 | return render( request, 'list.html',{ 'hosts': hosts,'rdss':rdss} )
44 |
45 | def addhost( request):
46 | if request.method == 'GET':
47 | h_name = request.REQUEST.get('hostname')
48 |
49 | return HttpResponse('ok')
50 |
--------------------------------------------------------------------------------
/cmdb/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os
3 | import sys
4 |
5 | if __name__ == "__main__":
6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cmdb.settings")
7 |
8 | from django.core.management import execute_from_command_line
9 |
10 | execute_from_command_line(sys.argv)
11 |
--------------------------------------------------------------------------------
/ecs.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding:utf-8 -*-
3 |
4 | import sys,os
5 | import urllib, urllib2
6 | import base64
7 | import hmac
8 | import hashlib
9 | from hashlib import sha1
10 | import time
11 | import uuid
12 | import json
13 | from optparse import OptionParser
14 | import ConfigParser
15 |
16 | access_key_id = '';
17 | access_key_secret = '';
18 | ecs_server_address = 'https://ecs.aliyuncs.com'
19 | CONFIGFILE = os.path.expanduser('~') + '/.aliyuncredentials'
20 | CONFIGSECTION = 'Credentials'
21 | cmdlist = '''
22 | Instance
23 | CreateInstance regionid imageid instancetype securitygroupid instancename internetmaxbandwidthout password
24 | SystemDisk.Category DataDisk.n.Category DataDisk.n.Size DataDisk.n.Snapshot InternetChargeType
25 | StopInstance
26 | RebootInstance
27 | ResetInstance
28 | ModifyInstanceSpec
29 | ModifyInstanceAttribute
30 | DescribeInstanceStatus
31 | DescribeInstanceAttribute
32 | DeleteInstance
33 |
34 | Disk
35 | AddDisk
36 | DeleteDisk
37 | DescribeInstanceDisks
38 | ReplaceSystemDisk
39 | ResetDisk
40 | ReInitDisk
41 |
42 | Snapshot
43 | CreateSnapshot
44 | DeleteSnapshot
45 | DescribeSnapshots
46 | DescribeSnapshotAttribute
47 |
48 |
49 | Images
50 | DescribeImages
51 | CreateImage
52 | DeleteImage
53 |
54 | IP
55 | AllocatePublicIpAddress
56 | ReleasePublicIpAddress
57 |
58 | SecurityGroup
59 | CreateSecurityGroup
60 | AuthorizeSecurityGroup
61 | DescribeSecurityGroupAttribute
62 | DescribeSecurityGroups
63 | RevokeSecurityGroup
64 | DeleteSecurityGroup
65 | JoinSecurityGroup
66 | LeaveSecurityGroup
67 |
68 | Common
69 | DescribeRegions
70 | GetMonitorData
71 | DescribeInstanceTypes
72 | '''
73 |
74 | def percent_encode(str):
75 | res = urllib.quote(str.decode(sys.stdin.encoding).encode('utf8'), '')
76 | res = res.replace('+', '%20')
77 | res = res.replace('*', '%2A')
78 | res = res.replace('%7E', '~')
79 | return res
80 |
81 | def compute_signature(parameters, access_key_secret):
82 | sortedParameters = sorted(parameters.items(), key=lambda parameters: parameters[0])
83 |
84 | canonicalizedQueryString = ''
85 | for (k,v) in sortedParameters:
86 | canonicalizedQueryString += '&' + percent_encode(k) + '=' + percent_encode(v)
87 |
88 | stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])
89 |
90 | h = hmac.new(access_key_secret + "&", stringToSign, sha1)
91 | signature = base64.encodestring(h.digest()).strip()
92 | return signature
93 |
94 | def compose_url(user_params):
95 | timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
96 |
97 | parameters = { \
98 | 'Format' : 'JSON', \
99 | 'Version' : '2014-05-26', \
100 | 'AccessKeyId' : access_key_id, \
101 | 'SignatureVersion' : '1.0', \
102 | 'SignatureMethod' : 'HMAC-SHA1', \
103 | 'SignatureNonce' : str(uuid.uuid1()), \
104 | 'TimeStamp' : timestamp, \
105 | }
106 |
107 | for key in user_params.keys():
108 | parameters[key] = user_params[key]
109 |
110 | signature = compute_signature(parameters, access_key_secret)
111 | parameters['Signature'] = signature
112 | url = ecs_server_address + "/?" + urllib.urlencode(parameters)
113 | return url
114 |
115 | def make_request(user_params, quiet=False):
116 | url = compose_url(user_params)
117 | request = urllib2.Request(url)
118 |
119 | try:
120 | conn = urllib2.urlopen(request)
121 | response = conn.read()
122 | except urllib2.HTTPError, e:
123 | print(e.read().strip())
124 | raise SystemExit(e)
125 |
126 | #make json output pretty, this code is copied from json.tool
127 | try:
128 | obj = json.loads(response)
129 | if quiet:
130 | return obj
131 | except ValueError, e:
132 | raise SystemExit(e)
133 | json.dump(obj, sys.stdout, sort_keys=True, indent=2)
134 | sys.stdout.write('\n')
135 |
136 | def configure_accesskeypair(args, options):
137 | if options.accesskeyid is None or options.accesskeysecret is None:
138 | print("config miss parameters, use --id=[accesskeyid] --secret=[accesskeysecret]")
139 | sys.exit(1)
140 | config = ConfigParser.RawConfigParser()
141 | config.add_section(CONFIGSECTION)
142 | config.set(CONFIGSECTION, 'accesskeyid', options.accesskeyid)
143 | config.set(CONFIGSECTION, 'accesskeysecret', options.accesskeysecret)
144 | cfgfile = open(CONFIGFILE, 'w+')
145 | config.write(cfgfile)
146 | cfgfile.close()
147 |
148 | def setup_credentials():
149 | config = ConfigParser.ConfigParser()
150 | try:
151 | config.read(CONFIGFILE)
152 | global access_key_id
153 | global access_key_secret
154 | access_key_id = config.get(CONFIGSECTION, 'accesskeyid')
155 | access_key_secret = config.get(CONFIGSECTION, 'accesskeysecret')
156 | except Exception, e:
157 | print("can't get access key pair, use config --id=[accesskeyid] --secret=[accesskeysecret] to setup")
158 | sys.exit(1)
159 |
160 | def describe_instances(regionid):
161 | user_params = {}
162 | user_params['Action'] = 'DescribeZones'
163 | user_params['RegionId'] = regionid
164 | obj = make_request(user_params, quiet=True)
165 |
166 | zones = []
167 | print('%21s %21s %10s %15s' % ('InstanceId', 'InstanceName', 'Status', 'InstanceType'))
168 | for zone in obj['Zones']['Zone']:
169 | user_params = {}
170 | user_params['Action'] = 'DescribeInstanceStatus'
171 | user_params['RegionId'] = regionid
172 | user_params['ZoneId'] = zone['ZoneId']
173 | instances = make_request(user_params, quiet=True)
174 | if len(instances) > 0:
175 | for i in instances['InstanceStatuses']['InstanceStatus']:
176 | instanceid = i['InstanceId']
177 | params = {}
178 | params['Action'] = 'DescribeInstanceAttribute'
179 | params['InstanceId'] = instanceid
180 | res = make_request(params, quiet=True)
181 | print('%21s %21s %10s %15s' % (res['InstanceId'], res['InstanceName'], res['Status'], res['InstanceType']))
182 |
183 | if __name__ == '__main__':
184 | parser = OptionParser("%s Action Param1=Value1 Param2=Value2\n DescribeImages RegionId=cn-qingdao ImageOwnerAlias=self" % sys.argv[0])
185 | parser.add_option("-i", "--id", dest="accesskeyid", help="specify access key id")
186 | parser.add_option("-s", "--secret", dest="accesskeysecret", help="specify access key secret")
187 |
188 | (options, args) = parser.parse_args()
189 | if len(args) < 1:
190 | parser.print_help()
191 | sys.exit(0)
192 |
193 | if args[0] == 'help':
194 | print cmdlist
195 | sys.exit(0)
196 | if args[0] != 'config':
197 | setup_credentials()
198 | else: #it's a configure id/secret command
199 | configure_accesskeypair(args, options)
200 | sys.exit(0)
201 |
202 | user_params = {}
203 | idx = 1
204 | if not sys.argv[1].lower().startswith('action='):
205 | user_params['action'] = sys.argv[1]
206 | idx = 2
207 |
208 | for arg in sys.argv[idx:]:
209 | try:
210 | key, value = arg.split('=')
211 | user_params[key.lower()] = value
212 | except ValueError, e:
213 | print(e.read().strip())
214 | raise SystemExit(e)
215 |
216 | if user_params['action'] == 'ls':
217 | describe_instances(user_params['regionid'])
218 | else:
219 | make_request(user_params)
220 |
221 |
--------------------------------------------------------------------------------