root/scripts/nfs/puppetlastgroups @ 482
321 | manumora | #!/usr/bin/env python
|
|
##############################################################################
|
|||
# -*- coding: utf-8 -*-
|
|||
# Project:
|
|||
# Module: puppetlastgroups
|
|||
334 | manumora | # Purpose: Gets info about last sinchronization date via puppet (grouped) from /var/lib/puppet/yaml/facts certs
|
|
321 | manumora | # Language: Python 2.5
|
|
# Date: 27-Abr-2012.
|
|||
# Ver: 27-Abr-2012.
|
|||
# Author: Francisco Mendez Palma
|
|||
# Manu Mora Gordillo
|
|||
# Copyright: 2012 - Francisco Mendez Palma <fmendezpalma @no-spam@ gmail.com>
|
|||
# 2012 - Manuel Mora Gordillo <manuito @ no-spam@ gmail.com>
|
|||
#
|
|||
# puppetlastgroups is free software: you can redistribute it and/or modify
|
|||
# it under the terms of the GNU General Public License as published by
|
|||
# the Free Software Foundation, either version 3 of the License, or
|
|||
# (at your option) any later version.
|
|||
# puppetlastgroups is distributed in the hope that it will be useful,
|
|||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|||
# GNU General Public License for more details.
|
|||
#
|
|||
##############################################################################
|
|||
import ldap
|
|||
import sys
|
|||
import subprocess
|
|||
import glob
|
|||
import os
|
|||
from datetime import datetime, timedelta
|
|||
337 | manumora | total_certs=0
|
|
total_elements=0
|
|||
total_withoutCert=0
|
|||
total_studentsLaptopsCerts=0
|
|||
total_studentsLaptopsWithoutCerts=0
|
|||
334 | manumora | all_hosts=[]
|
|
all_certs=[]
|
|||
337 | manumora | isPrinting=True
|
|
onlyHead=False
|
|||
334 | manumora | ||
321 | manumora | def humanize(delta):
|
|
days = delta.days
|
|||
hours = delta.seconds / 3600
|
|||
minutes = delta.seconds % 3600 / 60
|
|||
seconds = delta.seconds % 3600 % 60
|
|||
str = ""
|
|||
tStr = ""
|
|||
if days > 0:
|
|||
if days == 1: tStr = "day"
|
|||
else: tStr = "days"
|
|||
str = str + "%s %s" %(days, tStr)
|
|||
elif hours > 0:
|
|||
if hours == 1: tStr = "hour"
|
|||
else: tStr = "hours"
|
|||
str = str + "%s %s" %(hours, tStr)
|
|||
elif minutes > 0:
|
|||
if minutes == 1: tStr = "min"
|
|||
else: tStr = "mins"
|
|||
str = str + "%s %s" %(minutes, tStr)
|
|||
elif seconds > 0:
|
|||
if seconds == 1: tStr = "sec"
|
|||
else: tStr = "secs"
|
|||
str = str + "%s %s" %(seconds, tStr)
|
|||
return str
|
|||
# Obtiene lista nombres de maquinas a partir de los certificados almacenados en el servidor, en /var/lib/puppet/yaml/facts
|
|||
# asi como informacion del periodo que llevan sin sincronizar via puppet.
|
|||
334 | manumora | def gettimes():
|
|
321 | manumora | times = []
|
|
334 | manumora | global all_certs
|
|
321 | manumora | out = ''
|
|
import pdb
|
|||
for f in glob.glob("/var/lib/puppet/yaml/facts/*"):
|
|||
host = f.split('/')[-1].replace('.yaml', '')
|
|||
334 | manumora | all_certs.append(host)
|
|
321 | manumora | last = datetime.now() - datetime.fromtimestamp(os.stat(f)[9])
|
|
times.append((humanize(last), host, last))
|
|||
return times
|
|||
# Muestra en pantalla la info de la sincronizacion con codigo de colores
|
|||
def printtimes(times):
|
|||
337 | manumora | global all_hosts, isPrinting, onlyHead
|
|
334 | manumora | ||
321 | manumora | RED = '\033[91m'
|
|
GREEN = '\033[92m'
|
|||
ORANGE = '\033[93m'
|
|||
RESET = '\033[0m'
|
|||
for time in reversed(sorted(times, key=lambda x: x[2])):
|
|||
334 | manumora | all_hosts.append(time[1])
|
|
321 | manumora | ||
337 | manumora | if not onlyHead:
|
|
if time[2] < timedelta(hours=24) and isPrinting:
|
|||
print GREEN, "%10s ago: %s" % (time[0], time[1]), RESET
|
|||
elif time[2] < timedelta(hours=239) and isPrinting:
|
|||
print ORANGE, "%10s ago: %s" % (time[0], time[1]), RESET
|
|||
elif isPrinting:
|
|||
print RED, "%10s ago: %s" % (time[0], time[1]), RESET
|
|||
321 | manumora | def formatList(search):
|
|
from operator import itemgetter, attrgetter
|
|||
data=[]
|
|||
for i in search:
|
|||
classroom=i[0][0].replace("cn=","").replace(",ou=Group,dc=instituto,dc=extremadura,dc=es","")
|
|||
try:
|
|||
members=i[0][1]['memberUid']
|
|||
except:
|
|||
pass
|
|||
tuple = (classroom,members)
|
|||
data.append(tuple)
|
|||
tmp=sorted(data, key=itemgetter(0))
|
|||
return tmp
|
|||
334 | manumora | def formatOtherList(search,head):
|
|
323 | manumora | from operator import itemgetter, attrgetter
|
|
data=[]
|
|||
tmp=[]
|
|||
servers=search[0][0][1]['nisNetgroupTriple']
|
|||
for s in servers:
|
|||
tmp.append(s.replace("(","").replace(",-,-)",""))
|
|||
334 | manumora | tuple = (head,tmp)
|
|
323 | manumora | data.append(tuple)
|
|
tmp=sorted(data, key=itemgetter(1))
|
|||
return tmp
|
|||
321 | manumora | # Rutina principal
|
|
def puppetlast(times,search):
|
|||
import pdb
|
|||
337 | manumora | global total_certs, total_elements, total_withoutCert, isPrinting
|
|
335 | manumora | RED = '\033[91m'
|
|
RESET = '\033[0m'
|
|||
334 | manumora | ||
321 | manumora | for c in search:
|
|
if c[0]:
|
|||
times_temp=[]
|
|||
335 | manumora | # Eliminar tuplas vias
|
|
alumnos=[x for x in c[1] if x]
|
|||
321 | manumora | curso=c[0]
|
|
335 | manumora | without_cert=[]
|
|
321 | manumora | if len(alumnos)>1:
|
|
for a in alumnos:
|
|||
335 | manumora | cert_exists=False
|
|
321 | manumora | for t in times:
|
|
335 | manumora | if (a==t[1].split(".")[0]) and (a!=""):
|
|
321 | manumora | times_temp.append (t)
|
|
335 | manumora | cert_exists=True
|
|
if not cert_exists:
|
|||
without_cert.append(a)
|
|||
321 | manumora | ||
if len(times_temp)>1:
|
|||
337 | manumora | if isPrinting:
|
|
print "\n- "+curso+" ("+str(len(alumnos))+" elementos) ("+str(len(times_temp))+" certificados)"
|
|||
335 | manumora | if len(without_cert)>1:
|
|
for w in without_cert:
|
|||
337 | manumora | if w!="" and isPrinting and not onlyHead:
|
|
335 | manumora | print RED, "Sin certificado: "+w, RESET
|
|
337 | manumora | total_certs=total_certs+len(times_temp)
|
|
total_withoutCert=total_withoutCert+len(without_cert)
|
|||
total_elements=total_elements+len(alumnos)
|
|||
321 | manumora | printtimes(times_temp)
|
|
def ldapSearch(baseDN,filter,retrieveAttributes):
|
|||
try:
|
|||
l = ldap.open("ldap")
|
|||
except ldap.LDAPError, e:
|
|||
print "Error coneon LDAP"
|
|||
try:
|
|||
ldap_result_id = l.search(baseDN+",dc=instituto,dc=extremadura,dc=es", ldap.SCOPE_SUBTREE, filter, retrieveAttributes)
|
|||
result_set = []
|
|||
while 1:
|
|||
result_type, result_data = l.result(ldap_result_id, 0)
|
|||
if (result_data == []):
|
|||
break
|
|||
else:
|
|||
if result_type == ldap.RES_SEARCH_ENTRY:
|
|||
result_set.append(result_data)
|
|||
return result_set
|
|||
except ldap.LDAPError, e:
|
|||
print e
|
|||
334 | manumora | def cmpLists(list1, list2):
|
|
onlyInList1 = set(list1).difference(set(list2))
|
|||
onlyInList2 = set(list2).difference(set(list1))
|
|||
inTwoLists = set(list1) & set(list2)
|
|||
return { 'onlyInList1':onlyInList1, 'onlyInList2':onlyInList2, 'inTwoLists':inTwoLists }
|
|||
337 | manumora | def printHelp():
|
|
print "Modo de empleo: puppetlastgroups [OPCION] [AULA]\n"
|
|||
print " -g todos los grupos"
|
|||
print " -g 1ESOA un grupo concreto"
|
|||
print " -s servidores de aula"
|
|||
print " -p portatiles de profesores"
|
|||
print " -w workstations"
|
|||
print " -n no registrados en LDAP"
|
|||
print " -a todo"
|
|||
print " -e estadisticas"
|
|||
print " --help ayuda"
|
|||
334 | manumora | ||
337 | manumora | def printGroups():
|
|
global t
|
|||
if len (sys.argv)==3:
|
|||
filter="(&(groupType=school_class)(cn="+sys.argv[2]+"))"
|
|||
else:
|
|||
filter="(&(groupType=school_class))"
|
|||
321 | manumora | ||
337 | manumora | search = ldapSearch("ou=Group",filter,["memberUid"])
|
|
data = formatList(search)
|
|||
puppetlast(t,data)
|
|||
321 | manumora | ||
337 | manumora | def printLTSPServers():
|
|
global t
|
|||
323 | manumora | search = ldapSearch("cn=ltsp-server-hosts, ou=Netgroup","cn=*",["nisNetgroupTriple"])
|
|
334 | manumora | data = formatOtherList(search,"LTSP-Servers")
|
|
323 | manumora | puppetlast(t,data)
|
|
334 | manumora | ||
337 | manumora | def printWorkstations():
|
|
global t
|
|||
334 | manumora | try:
|
|
search = ldapSearch("cn=workstation-hosts, ou=Netgroup","cn=*",["nisNetgroupTriple"])
|
|||
data = formatOtherList(search,"Workstations")
|
|||
puppetlast(t,data)
|
|||
except:
|
|||
pass
|
|||
337 | manumora | # Portatiles de profesores. Debera tener la rama Netgroup->laptop-hosts
|
|
def printTeacherLaptops():
|
|||
global t
|
|||
334 | manumora | try:
|
|
search = ldapSearch("cn=laptop-hosts, ou=Netgroup","cn=*",["nisNetgroupTriple"])
|
|||
data = formatOtherList(search,"Portatiles profesores")
|
|||
puppetlast(t,data)
|
|||
except:
|
|||
pass
|
|||
337 | manumora | # Equipos desconocidos
|
|
def printUnknown():
|
|||
global all_certs, all_hosts, t
|
|||
comp=cmpLists(all_hosts, all_certs)
|
|||
l=[]
|
|||
for c in comp["onlyInList2"]:
|
|||
l.append(c.split(".")[0])
|
|||
334 | manumora | unknown=[]
|
|
337 | manumora | unknown.append(("No registrados en LDAP (con certificado)",l))
|
|
334 | manumora | puppetlast(t,unknown)
|
|
337 | manumora | def printStatistics():
|
|
global total_certs, total_elements, total_withoutCert, total_studentsLaptopsCerts, studentsLaptopsWithoutCerts
|
|||
print "\n############################################################"
|
|||
if total_studentsLaptopsCerts!=0:
|
|||
print "\nPortatiles alumnos:"
|
|||
print " - Total certificados: "+str(total_studentsLaptopsCerts)
|
|||
print " - Total sin certificado: "+str(total_studentsLaptopsWithoutCerts)
|
|||
print "\nTotal certificados: "+str(total_certs)
|
|||
print "Total sin certificado: "+str(total_withoutCert)
|
|||
print "Total elementos: "+str(total_elements)+"\n"
|
|||
t=gettimes()
|
|||
if len (sys.argv)<2:
|
|||
printHelp()
|
|||
exit()
|
|||
if sys.argv[1] == "-g":
|
|||
printGroups()
|
|||
printStatistics()
|
|||
elif sys.argv[1] == "-s":
|
|||
printLTSPServers()
|
|||
printStatistics()
|
|||
elif sys.argv[1] == "-w":
|
|||
printWorkstations()
|
|||
printStatistics()
|
|||
elif sys.argv[1] == "-p":
|
|||
printTeacherLaptops()
|
|||
printStatistics()
|
|||
elif sys.argv[1] == "-n":
|
|||
isPrinting=False
|
|||
printGroups()
|
|||
printLTSPServers()
|
|||
printWorkstations()
|
|||
printTeacherLaptops()
|
|||
isPrinting=True
|
|||
printUnknown()
|
|||
elif sys.argv[1] == "-a":
|
|||
printGroups()
|
|||
printLTSPServers()
|
|||
printWorkstations()
|
|||
printTeacherLaptops()
|
|||
printUnknown()
|
|||
printStatistics()
|
|||
elif sys.argv[1] == "-e":
|
|||
onlyHead=True
|
|||
printGroups()
|
|||
total_studentsLaptopsCerts=total_certs
|
|||
total_studentsLaptopsWithoutCerts=total_withoutCert
|
|||
printLTSPServers()
|
|||
printWorkstations()
|
|||
printTeacherLaptops()
|
|||
printUnknown()
|
|||
printStatistics()
|
|||
elif sys.argv[1] == "--help":
|
|||
printHelp()
|
|||
exit()
|
|||
else:
|
|||
printHelp()
|
|||
exit()
|