#settings.py
"""
Django settings for AutoCmdb project. Generated by 'django-admin startproject' using Django 2.0.6. For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '35d18e6vmo0k*xg#h=&kuer*t3a#@hv09@@kvz@=dd@dzw&!7w' # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api.apps.ApiConfig',
] MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
] ROOT_URLCONF = 'AutoCmdb.urls' TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
] WSGI_APPLICATION = 'AutoCmdb.wsgi.application' # Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} # Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
] # Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) # ————————03CMDB信息安全API接口交互认证————————
ASSET_AUTH_KEY = '299095cc-1330-11e5-b06a-a45e60bec08b' #认证的密码
ASSET_AUTH_TIME = 2 #认证的有效时间 #2秒
# ————————03CMDB信息安全API接口交互认证————————

#settings.py

 # auth.py
# ————————03CMDB信息安全API接口交互认证————————
import time #时间模块
import hashlib #哈希值
from AutoCmdb.settings import ASSET_AUTH_KEY #认证的密码
from AutoCmdb.settings import ASSET_AUTH_TIME #认证的有效时间
from django.http import JsonResponse #这个类是HttpRespon的子类 ENCRYPT_LIST = [
# {'encrypt': encrypt, 'time': timestamp
] #已认证的密码列表 def api_auth_method(request):
auth_key = request.META.get('HTTP_AUTH_KEY')#获取(META)元素 #‘时间密码’和 时间戳
print('‘时间密码’和 时间戳:',auth_key)
if not auth_key: #没有获取到值 就 #返回认证不通过
return False
sp = auth_key.split('|') # split()通过指定分隔符对字符串进行切片
if len(sp) != 2: #如果切片后的字符串 是2个 就 #返回认证不通过
return False
encrypt, timestamp = sp #给切片后的2个字符串 各设置一个变量
timestamp = float(timestamp) #float() 函数用于将整数和字符串转换成浮点数。
limit_timestamp = time.time() - ASSET_AUTH_TIME #设定服务器的时间戳
print('比较时间戳',limit_timestamp, timestamp)
if limit_timestamp > timestamp: #如果服务器的时间戳大于客户端的时间戳 就 #返回认证不通过
return False
#和客户端一样进行哈希加密
ha = hashlib.md5(ASSET_AUTH_KEY.encode('utf-8')) #认证的密码
ha.update(bytes("%s|%f" % (ASSET_AUTH_KEY, timestamp), encoding='utf-8'))#更新认证密码#密码+时间戳
result = ha.hexdigest() # 对‘时间密码’进行哈希
print('对比认证值:',result,encrypt)
if encrypt != result:#比较客户端哈希后的值和服务器哈希后的值是不是一样
return False#不一样就 #返回认证不通过
exist = False #是否认证过#标志位
del_keys = []
print('是否认证过,防止黑客:',ENCRYPT_LIST)
for k, v in enumerate(ENCRYPT_LIST):#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
print('下标:',k,'认证过的值和时间:', v)
m = v['time'] #已认证的密码列表 (#客户端的时间戳)
n = v['encrypt'] #已认证的密码列表( #客户端哈希后的值)
if m < limit_timestamp:#已认证的密码列表(#客户端的时间戳) #小于 #服务器的时间戳
del_keys.append(k) #添加下标到 del_keys 列表
continue #退出循环
if n == encrypt: #已认证的密码列表 #等于#客户端哈希后的值
exist = True#已认证 #标志位
for k in del_keys: #已经判断过的就删除 #客户端哈希后的值#客户端的时间戳
del ENCRYPT_LIST[k] #已认证的密码列表 #删除下标对应的值
if exist: #已认证 #标志位
return False #返回认证不通过
ENCRYPT_LIST.append({'encrypt': encrypt, 'time': timestamp})#客户端哈希后的值#客户端的时间戳
return True #返回认证通过 def api_auth(func):
def inner(request, *args, **kwargs):
if not api_auth_method(request): # 如果 return False #返回认证不通过
print("{'code': 1001, 'message': 'API授权失败'}")
return JsonResponse({'code': 1001, 'message': 'API授权失败'}, json_dumps_params={'ensure_ascii': False})
return func(request, *args, **kwargs) # 如果 return True #返回认证通过
return inner #执行#def inner(request, *args, **kwargs):
# ————————03CMDB信息安全API接口交互认证————————

# auth.py

 from django.shortcuts import render

 # Create your views here.

 # views.py
# ————————03CMDB信息安全API接口交互认证————————
from utils import auth
# ————————03CMDB信息安全API接口交互认证———————— # ————————02CMDB将服务器基本信息提交到API接口————————
import json #轻量级的文本数据交换格式
from django.views import View
from django.views.decorators.csrf import csrf_exempt #和HTML的{% csrf_token %}作用一样
from django.utils.decorators import method_decorator #安全通过 'django.middleware.csrf.CsrfViewMiddleware',
from django.http import JsonResponse#这个类是HttpRespon的子类
class AssetView(View):# http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
@method_decorator(csrf_exempt)#和HTML的{% csrf_token %}作用一样,安全通过 'django.middleware.csrf.CsrfViewMiddleware',
def dispatch(self, request, *args, **kwargs):
return super(AssetView, self).dispatch(request, *args, **kwargs) # ————————03CMDB信息安全API接口交互认证————————
@method_decorator(auth.api_auth) #装饰器
# ————————03CMDB信息安全API接口交互认证————————
def post(self, request, *args, **kwargs):#接受客户端到信息
server_info = json.loads(request.body.decode('utf-8'))
print('获取到的信息: ',type(server_info),server_info)
server_info = json.loads(server_info)#把字符串转换成字典
print('转换后的信息: ',type(server_info),server_info)
hostname = server_info['hostname']
print('主机名',hostname)
ret = {'code': 1000, 'message': '[%s]更新完成' % hostname}#返回到客户端到信息
print(ret)
return JsonResponse(ret)#这个类是HttpRespon的子类
# ————————02CMDB将服务器基本信息提交到API接口————————

# views.py


 #settings.py
# ————————01CMDB获取服务器基本信息————————
import os BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))##当前路径 # 采集资产的方式,选项有:agent(默认), salt, ssh
MODE = 'agent' # ————————01CMDB获取服务器基本信息———————— # ————————02CMDB将服务器基本信息提交到API接口————————
# 资产信息API
ASSET_API = "http://127.0.0.1:8000/api/asset"
# ————————02CMDB将服务器基本信息提交到API接口———————— # ————————03CMDB信息安全API接口交互认证————————
# 用于API认证的KEY
KEY = '299095cc-1330-11e5-b06a-a45e60bec08b' #认证的密码
# 用于API认证的请求头
AUTH_KEY_NAME = 'auth-key'
# ————————03CMDB信息安全API接口交互认证————————

#settings.py

 # client.py
# ————————01CMDB获取服务器基本信息————————
from src import plugins #__init__.py
from lib.serialize import Json #转成字符串或者模式 # ————————02CMDB将服务器基本信息提交到API接口————————
import requests #伪造页面访问
from config import settings #文件配置
# ————————02CMDB将服务器基本信息提交到API接口———————— # ————————03CMDB信息安全API接口交互认证————————
import hashlib
import time
# ————————03CMDB信息安全API接口交互认证———————— class AutoBase(object): # ————————02CMDB将服务器基本信息提交到API接口————————
def __init__(self):
self.asset_api = settings.ASSET_API #ASSET_API = "http://127.0.0.1:8000/api/asset" # ————————03CMDB信息安全API接口交互认证————————
self.key = settings.KEY # 用于API认证的KEY#KEY = '299095cc-1330-11e5-b06a-a45e60bec08b'
self.key_name = settings.AUTH_KEY_NAME # 'auth-key' API认证的请求头
# ————————03CMDB信息安全API接口交互认证———————— # ————————03CMDB信息安全API接口交互认证————————
def auth_key(self):#API接口认证
ha = hashlib.md5(self.key.encode('utf-8'))#认证的密码
time_span = time.time() #现在的时间戳 #1529819687.8867188
ha.update(bytes("%s|%f" % (self.key, time_span), encoding='utf-8'))#更新认证密码#密码+时间戳
encryption = ha.hexdigest() # 对‘时间密码’进行哈希
result = "%s|%f" % (encryption, time_span) #把‘时间密码’和 时间戳(解密用) 作为 API认证的请求头
print('‘时间密码’和 时间戳:',result)
return {self.key_name: result} # 'auth-key' API认证的请求头
# ————————03CMDB信息安全API接口交互认证———————— def post_asset(self, msg):#post方式向API接口提交资产信息
status = True#是否获取到信息
try:
# ————————03CMDB信息安全API接口交互认证————————
headers = {}
headers.update(self.auth_key())##认证的密码
# ————————03CMDB信息安全API接口交互认证————————
response = requests.post(
url=self.asset_api,
# ————————03CMDB信息安全API接口交互认证————————
headers=headers,
# ————————03CMDB信息安全API接口交互认证————————
json=msg
)
except Exception as e:
response = e
status = False #获取信息时出现错误
print(response.json())
# ————————02CMDB将服务器基本信息提交到API接口———————— def process(self):#派生类需要继承此方法,用于处理请求的入口
raise NotImplementedError('您必须实现过程的方法') class AutoAgent(AutoBase):
def process(self):
server_info = plugins.get_server_info()#获取本地基本信息
server_json = Json.dumps(server_info.data)#json.dumps将 Python 对象编码成 JSON 字符串
print('提交资产信息:',server_json)
# ————————01CMDB获取服务器基本信息———————— # ————————02CMDB将服务器基本信息提交到API接口————————
self.post_asset(server_json)# post方式向接口提交资产信息
# ————————02CMDB将服务器基本信息提交到API接口————————

# client.py


Django项目:CMDB(服务器硬件资产自动采集系统)--03--03CMDB信息安全API接口交互认证的更多相关文章

  1. Django项目:CMDB(服务器硬件资产自动采集系统)--11--07CMDB文件模式测试采集硬件数据

    #settings.py # ————————01CMDB获取服务器基本信息———————— import os BASEDIR = os.path.dirname(os.path.dirname(o ...

  2. Django项目:CMDB(服务器硬件资产自动采集系统)--12--08CMDB采集硬件数据日志记录

    #settings.py # ————————01CMDB获取服务器基本信息———————— import os BASEDIR = os.path.dirname(os.path.dirname(o ...

  3. Django项目:CMDB(服务器硬件资产自动采集系统)--07--06CMDB测试Linux系统采集硬件数据的命令02

    #settings.py """ Django settings for AutoCmdb project. Generated by 'django-admin sta ...

  4. Django项目:CMDB(服务器硬件资产自动采集系统)--06--06CMDB测试Linux系统采集硬件数据的命令01

    #base.py # ————————01CMDB获取服务器基本信息———————— from config import settings #配置文件 class BasePlugin(object ...

  5. Django项目:CMDB(服务器硬件资产自动采集系统)--05--05CMDB采集硬件数据的插件

    #__init__.py # ————————05CMDB采集硬件数据的插件———————— from config import settings import importlib # —————— ...

  6. Django项目:CMDB(服务器硬件资产自动采集系统)--04--04CMDB本地(Agent)模式客户端唯一标识(ID)

    # client.py # ————————01CMDB获取服务器基本信息———————— from src import plugins #__init__.py from lib.serializ ...

  7. Django项目:CMDB(服务器硬件资产自动采集系统)--02--02CMDB将服务器基本信息提交到API接口

    AutoCmdb # urls.py """AutoCmdb URL Configuration The `urlpatterns` list routes URLs t ...

  8. Django项目:CMDB(服务器硬件资产自动采集系统)--08--06CMDB测试Linux系统采集硬件数据的命令03

    https://www.virtualbox.org/wiki/Downloads https://mirrors.aliyun.com/centos/7/isos/x86_64/ http://ww ...

  9. Django项目:CMDB(服务器硬件资产自动采集系统)--10--06CMDB测试Linux系统采集硬件数据的命令05

    cd /py/AutoClient/bin python3 auto-client.py /usr/local/python3/bin/pip install requests python3 aut ...

随机推荐

  1. HDU - 1560 DNA sequence

    给你最多8个长度不超过5的DNA系列,求一个包含所有系列的最短系列. 迭代加深的经典题.(虽然自己第一次写) 定一个长度搜下去,搜不出答案就加深大搜的限制,然后中间加一些玄学的减枝 //Twenty ...

  2. VS2010-MFC(常用控件:树形控件Tree Control 上)

    转自:http://www.jizhuomi.com/software/200.html 前面两节讲了列表视图控件List Control,这一节开始介绍一种特殊的列表--树形控件Tree Contr ...

  3. VS2010-MFC(对话框:文件对话框)

    转自:http://www.jizhuomi.com/software/173.html 一 文件对话框的分类       文件对话框分为打开文件对话框和保存文件对话框,相信大家在Windows系统中 ...

  4. (3)mysql表和字段的操作

    创建表 create table name( id int, student ) ); 查看表结构 ****常用**** describe 表名; 修改表名 老表 rename 新表 ALTER TA ...

  5. JSP页面静态化总结之一使用URLRewrite实现url地址伪静态化

    JSP页面静态化总结之一使用URLRewrite实现url地址伪静态化 1使用URLRewrite实现url地址伪静态化1.1URLRewirte的用处 1.满足搜索引擎的要求. 2.隐藏技术实现,提 ...

  6. 关于tomcat配置了虚拟路径,但是在Idea中无法生效的问题

    1. 确认 tomcat 的server.xml 文件中配置的虚拟路径是否正确 其中,path表示访问的虚拟路径,docBase表示真实路径 2. Idea 服务器配置中是否勾选 “Deploy ap ...

  7. POJ 1743-POJ - 3261~后缀数组关于最长字串问题

    POJ 1743 题意: 有N(1 <= N <=20000)个音符的序列来表示一首乐曲,每个音符都是1~~88范围内的整数,现在要找一个重复的主题.“主题”是整个音符序列的一个子串,它需 ...

  8. 帝国cms学习

    手册地址1 手册地址2 入门 安装: 将下载的upload里的文件上传到网站更目录 然后 域名/e/install/index.php Warning: Use of undefined consta ...

  9. 模块介绍/time/os...

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...

  10. 【HZOI2015】帕秋莉的超级多项式

    题面 题目分析 超级模板题: 多项式乘法 多项式求逆 多项式开根 多项式求导 多项式求积分 多项式求对数 多项式求自然对数为底的指数函数 多项式快速幂 代码实现 #include<iostrea ...