def KeyList(request):
    usersession = request.session.get('user_id')
    user_name = request.session.get('user_name')
    if request.method == 'GET':
        Accepted = Minions.objects.filter(status='Accepted')
        Unaccepted = Minions.objects.filter(status='Unaccepted')
        Rejected = Minions.objects.filter(status='Rejected')
        froms = KeyManager()
        return render(request, 'saltadmin/key_list.html', locals())

    if request.method == 'POST':
        minion = request.POST.get('minion')
        status = request.POST.get('status')
        Minion_data = Minions.objects.get(minion=minion)
        Minion_data.status = status
        Minion_data.save()
        Operation.objects.create(Opuser=user_name,
                                 Opaction=u'修改 minion Key状态 %s to %s' %
                                 (Minion_data.minion, status))
        url = Minion_data.saltserver.url

        username = Minion_data.saltserver.username
        password = Minion_data.saltserver.password

        salt = SaltApi(url, username, password)
        if status == 'Accepted':
            ret = salt.AcceptKey(minion)
        elif status == 'Unaccepted':
            ret = salt.DeleteKey(minion)
        elif status == 'Rejected':
            ret = salt.RejectKey(minion)

        return HttpResponse('OK')
Esempio n. 2
0
def SaltGrains(minion):
    salt = SaltApi()
    print "------------------------"
    print "%s" % minion['id']
    data = salt.grainsall(minion['id'])
    print "------------------------"
    return data
Esempio n. 3
0
def SaltGrainsAll():
    salt = SaltApi()
    print "----------Grainsall------------"
    clientkey = salt.List_all_keys()['minions']
    for i in clientkey:
        data = salt.grainsall(i)
    return clientkey
def DeployResult(request, jid):
    if request.method == 'GET':
        minions_list = request.GET.get('minion')
        savelogid = request.GET.get('savelogid')

        saltm = Minions.objects.get(minion=minions_list.split(',')[0])

        url = saltm.saltserver.url
        username = saltm.saltserver.username
        password = saltm.saltserver.password

        salt = SaltApi(url, username, password)
        resultdata = salt.salt_runner(jid)
        resultdata = JobResultFromat(resultdata)

        #print savelogid
        #logs = CmdRunLog.objects.get(id=savelogid)
        #logs.runresult=resultdata
        #logs.runsuccess=len(resultdata)
        #logs.save()
        #print yaml.load_all(resultdata)

        ret = {'minion': minions_list, 'resultdata': resultdata}

        return HttpResponse(json.dumps(ret))
def RemoteCmd(request):
    usersession = request.session.get('user_id')
    user_name = request.session.get('user_name')

    if request.method == 'GET':
        GroupData = MinionGroup.objects.all()
        #hosts = """[ {type: 1, list: [{ text: 'yang', id: 1}, {text: 'asdasd',id: 4}]}, }]"""

        groupall = []
        for g in GroupData:
            group = {}
            list = []
            for m in g.minions.all():
                dir = {}
                dir['text'] = m.minion
                dir['id'] = m.minion
                list.append(dir)

            group['type'] = g.id
            group['list'] = list
            groupall.append(group)
        groupall = json.dumps(groupall)
        return render(request, 'saltadmin/salt_cmd.html', locals())

    else:
        if not request.POST.get('minion'):
            minions_id = request.POST.get('minion_group')
            minions_data = MinionGroup.objects.get(id=minions_id).minions.all()

        else:
            minions_data = request.POST.getlist('minion')

        minions_list = ''
        for m in minions_data:
            minions_list += str(m) + ','
        minions_list = minions_list.strip(',')

        cmd = request.POST.get('cmd')
        #必须是同一台master上的才能为一个组,这样只需要查询一个就可

        saltm = Minions.objects.get(minion=minions_list.split(',')[0])
        url = saltm.saltserver.url
        username = saltm.saltserver.username
        password = saltm.saltserver.password

        salt = SaltApi(url, username, password)
        jid = salt.shell_remote_execution(minions_list, cmd)
        Operation.objects.create(Opuser=user_name, Opaction=u'执行命令 %s' % cmd)

        savelog = CmdRunLog.objects.create(user=user_name,
                                           target=minions_list,
                                           cmd=cmd,
                                           total=len(minions_list.split(',')))

        ret = {'jid': jid, 'minion': minions_list, 'savelogid': savelog.id}
        return HttpResponse(json.dumps(ret))
def jobdetail(request):
    if request.method == 'GET':
        jid = request.GET.get('jid')
        print jid
        jiddata = SaltJobs.objects.get(jid=jid)
        masterdata = SaltServer.objects.get(url=jiddata.saltserver)
        url = masterdata.url
        username = masterdata.username
        password = masterdata.password

        salt = SaltApi(url, username, password)
        resultdata = salt.salt_runner(jid)
        return HttpResponse(json.dumps(resultdata))
Esempio n. 7
0
def GetJobs(url, username, password):
    salt = SaltApi(url, username, password)

    data = salt.runner("jobs.list_jobs")

    for j, info in data.items():
        if SaltJobs.objects.filter(jid=j):
            pass
        else:
            SaltJobs.objects.create(jid=j,
                                    args=info['Arguments'],
                                    function=info['Function'],
                                    startTime=info['StartTime'],
                                    target=info['Target'],
                                    user=info['User'],
                                    saltserver=url)
def SaltMinionGrains(request):
    id = request.GET.get('minion')
    action = request.GET.get('action')
    Minion_data = MinionStatus.objects.get(id=id)
    url = Minion_data.minion.saltserver.url
    username = Minion_data.minion.saltserver.username
    password = Minion_data.minion.saltserver.password
    salt = SaltApi(url, username, password)

    if str(action) == 'grains':
        Data = salt.grainsall(str(Minion_data.minion))
    elif str(action) == 'pillar':
        Data = salt.pillarall(str(Minion_data.minion))
    else:
        Data = {"msg": '无法查询'}
    return HttpResponse(json.dumps(Data))
Esempio n. 9
0
def GetALLkeys():
    saltmaster = SaltServer.objects.all()

    for server in saltmaster:
        salt = SaltApi(server.url, server.username, server.password)
        minions, minions_pre, minions_rej, minions_deny = salt.List_all_keys()
        for i in minions:
            try:
                Minions.objects.create(minion=i,
                                       saltserver=server,
                                       status="Accepted")
            except:
                minion = Minions.objects.get(minion=i)
                minion.status = 'Accepted'
                minion.save()
        for pre in minions_pre:
            try:
                Minions.objects.create(minion=pre,
                                       saltserver=server,
                                       status="Unaccepted")
            except:
                minion = Minions.objects.get(minion=pre)
                minion.status = 'Unaccepted'
                minion.save()

        for rej in minions_rej:
            try:
                Minions.objects.create(minion=rej,
                                       saltserver=server,
                                       status="Rejected")
            except:
                minion = Minions.objects.get(minion=rej)
                minion.status = 'Rejected'
                minion.save()

        for deny in minions_deny:
            try:
                Minions.objects.create(minion=deny,
                                       saltserver=server,
                                       status="Denied")
            except:
                minion = Minions.objects.get(minion=deny)
                minion.status = 'Denied'
                minion.save()
Esempio n. 10
0
def UpdateMinionInfo(mininboj, minions, url, username, password):
    salt = SaltApi(url, username, password)
    alive_minions = salt.Saltalive(minions)

    print alive_minions
    if minions in alive_minions:
        minion_status = True
    else:
        minion_status = False

    try:
        MinionStatus.objects.create(minion=mininboj,
                                    minion_status=minion_status)
    except:
        saltminion = MinionStatus.objects.get(minion=mininboj)
        alive_old = MinionStatus.objects.get(minion=mininboj).minion_status

        if minion_status != alive_old:
            saltminion.alive_time_last = datetime.datetime.now()
            saltminion.minion_status = minion_status
        print "-------------------------------%s" % (minion_status, )
        saltminion.alive_time_now = datetime.datetime.now()
        saltminion.save()
Esempio n. 11
0
def UpdateServerInfo(serverid):
    salt = SaltApi('http://127.0.0.1:8000/', 'roddy', 'roudy_123456')
    serverdata = Server.objects.get(id=serverid)
    saltid = serverdata.saltid
    data = salt.grainsall(saltid)
    ServerInfo = data

    #CPU信息
    CpuData = ServerCPUInfo(ServerInfo, saltid)
    CpuINFO = CpuData.ServerCPU()

    #DISK信息
    DiskData = ServerDiskInfo(ServerInfo, saltid)
    DiskINFO = DiskData.ServerDISK()

    #NIC信息
    NICData = ServerNICInfo(ServerInfo, saltid)
    NICINFO = NICData.ServerNIC()
    BaseINFO = CpuINFO['Serverbaseinfo']

    #--------------------------更新CPU信息-------------------------
    parentsn = CpuINFO['Serverbaseinfo']['sn']
    Cpudict = CpuINFO['servercpuinfo']
    Thread = Cpudict['thread']
    L1cache = Cpudict['L1cache']
    L2cache = Cpudict['L2cache']
    L3cache = Cpudict['L3cache']
    model = Cpudict['model']
    Vendordata = Cpudict['model']
    Vendor = Vendordata.split()[0]
    Architecture = Cpudict['architecture']
    cpu_mhz = Cpudict['cpu_mhz']
    uuid = Cpudict['uuid']

    if Cpu.objects.filter(parent_sn=parentsn):
        ChangeCpu = Cpu.objects.get(parent_sn=parentsn)
        ChangeCpu.Thread = Thread
        ChangeCpu.L1cache = L1cache
        ChangeCpu.L2cache = L2cache
        ChangeCpu.L3cache = L3cache
        ChangeCpu.Vendor = Vendor
        ChangeCpu.model = model
        ChangeCpu.Architecture = Architecture
        ChangeCpu.cpu_mhz = cpu_mhz
        ChangeCpu.parent_sn = parentsn
        ChangeCpu.uuid = uuid
        ChangeCpu.save()
    else:
        NewCpu = Cpu(
            Thread=Thread,
            uuid=uuid,
            model=model,
            Architecture=Architecture,
            cpu_mhz=cpu_mhz,
            L1cache=L1cache,
            Vendor=Vendor,
            L2cache=L2cache,
            L3cache=L3cache,
            parent_sn=parentsn,
        )
        NewCpu.save()

    #--------------------------更新服务器信息------------------------
    serverdata.hostname = BaseINFO['hostname']
    serverdata.sn = BaseINFO['sn']
    if Cpu.objects.filter(parent_sn=BaseINFO['sn']):
        Cpuid = Cpu.objects.get(parent_sn=parentsn)
        serverdata.cpu = Cpuid

    serverdata.cpu_count = BaseINFO['cpu_count']
    serverdata.saltid = BaseINFO['saltid']
    serverdata.mem = BaseINFO['mem']
    serverdata.swap = BaseINFO['swap']
    serverdata.platform = BaseINFO['platform']
    serverdata.system = BaseINFO['system']
    serverdata.version = BaseINFO['version']
    serverdata.cpu_core_count = BaseINFO['cpu_core_count']
    serverdata.save()

    #---------------------------获取网卡信息----------------------------
    Nicdict = NICINFO['servernicinfo']['nicinfo']
    parentsn = NICINFO['Serverbaseinfo']['sn']
    for nicname, nicvalue in Nicdict.items():
        #排除lo和docker网卡
        if nicname not in [
                'eth1', 'eth0', 'em1', 'em0', 'p3p1', 'p1p1', 'p8p1'
        ]:
            continue
        if nicvalue.get('inet'):
            mac = nicvalue['hwaddr']
            Model = nicvalue['Model']
            nicstatus = nicvalue['up']
            uuid = nicvalue['uuid']
            name = nicname
            ip = nicvalue['inet'][0]['address']
            netmask = nicvalue['inet'][0]['netmask']

            if NIC.objects.filter(mac=mac):
                OldNic = NIC.objects.get(mac=mac)
                OldNic.uuid = uuid
                OldNic.name = name
                OldNic.model = Model
                OldNic.ip = ip
                OldNic.mac = mac
                OldNic.parent_sn = parentsn
                OldNic.netmask = netmask
                OldNic.nicstatus = nicstatus
                OldNic.save()
            else:
                Newnic = NIC(uuid=uuid,
                             name=name,
                             model=Model,
                             parent_sn=parentsn,
                             ip=ip,
                             mac=mac,
                             netmask=netmask,
                             nicstatus=nicstatus)
                Newnic.save()
        else:
            continue

    #删除以前网卡信息
    for nic in serverdata.nic.all():
        serverdata.nic.remove(nic)

    #添加网卡到服务器
    nicdata = NIC.objects.filter(parent_sn=parentsn)
    for nic in nicdata:
        sdata = Server.objects.get(sn=parentsn)
        sdata.nic.add(nic)

    #---------------获取硬盘信息-------------------------
    parentsn = DiskINFO['Serverbaseinfo']['sn']
    Diskdict = DiskINFO['serverdiskinfo']['diskinfo']
    for diskname, diskvalue in Diskdict.items():
        name = diskvalue['name']
        uuid = diskvalue['uuid']
        capacity = diskvalue['size']
        disk_type = diskvalue['type']

        if Disk.objects.filter(uuid=uuid):
            for OldDisk in Disk.objects.filter(parent_sn=parentsn):
                OldDisk.name = name
                OldDisk.capacity = capacity
                OldDisk.parent_sn = parentsn
                OldDisk.disk_type = disk_type
                OldDisk.save()
        else:
            NewDisk = Disk(name=name,
                           uuid=uuid,
                           parent_sn=parentsn,
                           capacity=capacity,
                           disk_type=disk_type)
            NewDisk.save()

    #删除以前磁盘信息
    for disk in serverdata.disk.all():
        serverdata.disk.remove(disk)

    #添加磁盘到服务器
    diskdata = Disk.objects.filter(parent_sn=parentsn)
    for disk in diskdata:
        sdata = Server.objects.get(sn=parentsn)
        sdata.disk.add(disk)

    serverinfo = {}
    Info_Data = Server.objects.get(id=serverid)
    serverinfo['hostname'] = Info_Data.hostname
    serverinfo['last_update'] = Info_Data.update_time.strftime(
        "%Y-%m-%d %H:%M:%S")
    serverinfo['sn'] = Info_Data.sn
    serverinfo['cpu'] = Info_Data.cpu_count
    niclist = []
    for i in Info_Data.nic.all():
        niclist.append(i.ip)
    serverinfo['nic'] = niclist

    disklist = []
    for d in Info_Data.disk.all():
        disklist.append(d.name)
    serverinfo['disk'] = disklist

    return {'result': serverinfo}
Esempio n. 12
0
def SoftInstall(request):
    usersession = request.session.get('user_id')
    user_name = request.session.get('user_name')
    if request.method == 'GET':
        SoftModuleData = Modules.objects.all()
        GroupData = MinionGroup.objects.all()
        # hosts = """[ {type: 1, list: [{ text: 'yang', id: 1}, {text: 'asdasd',id: 4}]}, }]"""

        groupall = []
        for g in GroupData:
            group = {}
            list = []
            for m in g.minions.all():
                dir = {}
                dir['text'] = m.minion
                dir['id'] = m.minion
                list.append(dir)

            group['type'] = g.id
            group['list'] = list
            groupall.append(group)
        groupall = json.dumps(groupall)

        return render(request, 'saltadmin/saltmodule_deploy.html', locals())

    else:
        if not request.POST.get('minion'):
            minions_id = request.POST.get('minion_group')
            minions_data = MinionGroup.objects.get(id=minions_id).minions.all()
        else:
            minions_data = request.POST.getlist('minion')

        minions_list = ''
        for m in minions_data:
            minions_list += str(m) + ','
        minions_list = minions_list.strip(',')

        software = request.POST.getlist('software')
        salt_env = request.POST.get('env')

        soft = ''
        for i in software:
            soft += i + ','
        soft = soft.strip(',')

        saltm = Minions.objects.get(minion=minions_list.split(',')[0])

        url = saltm.saltserver.url
        username = saltm.saltserver.username
        password = saltm.saltserver.password

        salt = SaltApi(url, username, password)

        jid = salt.Softwarete_deploy(
            minions_list,
            arg=["saltenv=%s" % (salt_env),
                 str(soft), 'test=True'])

        Operation.objects.create(Opuser=user_name, Opaction=u'部署软件 %s' % soft)
        #savelog = CmdRunLog.objects.create(user=user_name, target=minions_list, cmd=cmd, total=len(minions_list.split(',')))

        ret = {'jid': jid, 'minion': minions_list, 'savelogid': 1}
        return HttpResponse(json.dumps(ret))