上次和大家聊到salt-api,今天把平台完善一下,支持正则*,+。
仍然是用上次的模块,增加了HOST,GROUP的models,修改了views,增加了正则的处理模块。
直接上代码:

正则处理模块 utils.py:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from models import Host
import re

def get_all_minion(tgt):
    target_list = tgt.split(',')
    minion_list = []
    all_minion_ip_list = []
    if '*' in target_list:
        all_host = Host.objects.all().values()
        for i in all_host:
            minion_list.append(i["ip"])
        minion_list_set = set(minion_list)
    else:
        all_host = Host.objects.all()
        for minion in all_host:
            all_minion_ip_list.append(minion.ip)
        for target in target_list:
            if '*' or '+' in target:
                target_replace_point = target.replace('.','\.')
                if '*':
                    target_replace_star = target_replace_point.replace('*', '.*')
                if '+':
                    target_replace_star = target_replace_point.replace('+', '.+')
                target_string = r'%s' % target_replace_star
                pattern = re.compile(target_string)
                for minion_ip in all_minion_ip_list:
                    match_ip = pattern.match(minion_ip)
                    if match_ip:
                        match_minion_ip_data = Host.objects.get(ip=minion_ip)
                    minion_list.append(match_minion_ip_data.ip)
            else:
                target_replace_none = target.replace('.','')
                if target_replace_none.isdigit():
                    try:
                        match_minion_ip_data = Host.objects.get(ip=target)
                        minion_list.append(match_minion_ip_data.ip)
                    except Host.DoesNotExist:
                        print 'Without this IP on host list. IP:{0}'.format(target)
                else:
                    try:
                        mtach_minion_id_data = Host.objects.get(ip=target)
                        minion_list.append(target)
                    except Host.DoesNotExist:
                        print("MinionID don't exsit. Minion id:{0}".format(target))

    minion_list_set = set(minion_list)
    return minion_list_set

models.py增加了主机组和主机:

class Group(models.Model):
    name = models.CharField(u"组",max_length=100)
    class Meta:
        verbose_name = u"组"
        verbose_name_plural = verbose_name
    def __unicode__(self):
        return u'%s' % (self.name)

class Host(models.Model):
    ip = models.CharField(u"ip地址",max_length=15)
    group = models.ForeignKey(Group)
    class Meta:
        verbose_name = u"服务器"
        verbose_name_plural = verbose_name
    def __unicode__(self):
        return u'%s' % (self.ip)

views.py:

from django.shortcuts import render, HttpResponse, HttpResponseRedirect,render_to_response
from models import *
from saltapi import salt_api
from django.http import JsonResponse
import json
import xadmin
from util import get_all_minion
from forms import *

def index(request):
    result_minion = []
    Register_form = accect_cmdForm()
    all_group = Group.objects.all()
    accect = []
    context = accect_cmd.objects.values()
    for i in context:
        accect.append(i["command"])
    if request.method == "POST":
        key = request.POST.get('key')
        if not key:
            data = {key: "请输入主机"}
            return JsonResponse(data, safe=False)
        cmd = request.POST.get('cmd')
        if not cmd:
            data = {key: "请输入命令"}
            return JsonResponse(data, safe=False)
        all_host_set = get_all_minion(key)
        if len(all_host_set) > 0 and cmd.split()[0] in accect:
            tgt_list_to_str = ','.join(list(all_host_set))
            spi = salt_api.SaltAPI('https://ip:8000', 'username', 'password')
            result = spi.masterToMinionContent(tgt_list_to_str, 'cmd.run', cmd)
            for i in result:
                result_minion.append(i)
            result_not_minion = all_host_set - set(result_minion)
            for x in result_not_minion:
                result[x]="该主机未返回结果!!!"
            return JsonResponse(result, safe=False)
        if len(all_host_set) > 0 and not cmd.split()[0] in accect:
            data = {key:"请检查命令是否正确或命令超权限,请联系管理员!"}
            return JsonResponse(data, safe=False)
        else:
            data = {key:"数据库未查到该主机"}
            return JsonResponse(data, safe=False)
    else:
        return render(request, 'index.html', {'Register_form': Register_form,'all_group':all_group})

效果

salt平台完善正则匹配_第1张图片

salt平台完善正则匹配_第2张图片

salt平台完善正则匹配_第3张图片