CMDB学习之六 --客户端请求测试,服务端api优化
客户端使用agent 请求测试,agent使用的POST 请求,使用requests模块
本地采集,汇报服务端
#!/usr/bin/env python # -*- coding:utf-8 -*- from .base import BaseHandler from ..plugins import get_server_info import requests import json class AgnetHandler(BaseHandler): def cmd(self,command,hostname=None): import subprocess return subprocess.getoutput(command) def handler(self): """ Agent模式下处理资产采集:硬盘、内存、网卡 :return: """ print('agent模式') #调用pulugins.disk /plugins.momory /plugins.nerwork info = get_server_info(self) # print(info) r1 = requests.post( url='http://127.0.0.1:8000/api/asset', data=json.dumps(info) ) print(r1)
salt 和ssh请求 首先要获取服务端 ,没有采集的主机列表,然后根据主机列表进行采集。
1. get请求获取主机列表
2、发起远程采集数据,汇报服务器
两方法都有 采集都发起远程和汇报服务器的功能,所有在基类实现方法,然后 方法继承基类 SSHhandSaltHandler
#!/usr/bin/env python # -*- coding:utf-8 -*- from ..plugins import get_server_info import json import requests class BaseHandler(object): def cmd(self,command,hostname=None): ''' 约束派生类 :return: ''' raise NotImplementedError('cmd() must Implemented.') def handler(self): ''' 约束派生类 :return: ''' raise NotImplementedError('handler() must Implemented.') class SSHhandSaltHandler(BaseHandler): def handler(self): """ Salt模式下处理资产采集 :return: """ print('salt模式或者ssh模式') r1 = requests.get(url='http://127.0.0.1:8000/api/asset') host_list = r1.json() print(host_list) from concurrent.futures import ThreadPoolExecutor pool = ThreadPoolExecutor(10) for host in host_list: pool.submit(self.task, host) def task(self, hostname): # 资产采集并且汇报 info = get_server_info(self) # print(info) r1 = requests.post( url='http://127.0.0.1:8000/api/asset', data=json.dumps(info) ) print(r1) print(r1.text)
#!/usr/bin/env python # -*- coding:utf-8 -*- from .base import SSHhandSaltHandler class SaltHandler(SSHhandSaltHandler): def cmd(self, command, hostname=None): """ 调用saltstack远程连接主机并执行命令(saltstack的master) :param hostname:主机名 :param command: 要执行的命令 :return: """ import salt.client #安装salt local = salt.client.LocalClient() result = local.cmd(hostname, 'cmd.run', [command]) return result[hostname]
#!/usr/bin/env python # -*- coding:utf-8 -*- from .base import SSHhandSaltHandler from config import settings class SSHHandler(SSHhandSaltHandler): def cmd(self, command, hostname=None): """ 调用paramiko远程连接主机并执行命令,依赖rsa :param hostname:主机名 :param command: 要执行的命令 :return: """ import paramiko private_key = paramiko.RSAKey.from_private_key_file(settings.SSH_PRIVATE_KEY) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=hostname, port=settings.SSH_PORT, username=settings.SSH_USER, pkey=private_key) stdin, stdout, stderr = ssh.exec_command(command) result = stdout.read() ssh.close() return result
##################下面是django服务端#######################
下面使用多种方式的api
from django.shortcuts import render,HttpResponse,redirect,reverse from django.views.decorators.csrf import csrf_exempt import json # Create your views here. @csrf_exempt def asset(request): if request.method == 'GET': host_list = ['c1.com','c2.com'] return HttpResponse(json.dumps(host_list)) #序列化 # print(request.body) #原始数据 # print(request.POST) #url编码的格式 "hostname=c1.com&memory=...." ret =json.loads(request.body.decode('utf-8')) print(ret) return HttpResponse("接受成功") # CBV加装饰器,忽略csrf验证 # from django.utils.decorators import method_decorator # from django.views import View # # @method_decorator(csrf_exempt,name='dispatch') #这个装饰器比较特殊不能直接加到类中的方法,方法一 # class Asset(View): # # # 这个装饰器比较特殊不能直接加到类中的方法,方法二 # @method_decorator(csrf_exempt) # def dispatch(self,request,*args,**kwargs): # return super().dispatch(request,*args,**kwargs) # # def get(self,request): # host_list = ['c1.com', 'c2.com'] # return HttpResponse(json.dumps(host_list)) # 序列化 # # def post(self,request): # ret = json.loads(request.body.decode('utf-8')) # print(ret) # return HttpResponse("接受成功") #使用rest_framework ,首先要安装pip去安装Djangorestframework ,这个模块 # 在Django的settings中注册app from rest_framework.views import APIView from rest_framework.response import Response class Asset(APIView): def get(self,request): host_list = ['c1.com', 'c2.com'] return Response(host_list) def post(self,request): ret = json.loads(request.body.decode('utf-8')) print(ret) return HttpResponse("接受成功")
Django提供的 rest_framework 需要安装模块导入使用,方便简洁,rest_framework是一个独立的app,所以在Django配置文件中注册
页面结果;