source: client/engine/Inventory.lib @ 6dedc02

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since 6dedc02 was 6dedc02, checked in by ramon <ramongomez@…>, 10 years ago

#713: Incluir tipo de arranque BIOS o UEFI en inventario de hardware.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@4660 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100755
File size: 16.1 KB
Line 
1#!/bin/bash
2#/**
3#@file    Inventory.lib
4#@brief   Librería o clase Inventory
5#@class   Inventory
6#@brief   Funciones para recogida de datos de inventario de hardware y software de los clientes.
7#@version 1.1.0
8#@warning License: GNU GPLv3+
9#*/
10
11
12#/**
13#         ogGetArch
14#@brief   Devuelve el tipo de arquitectura del cliente.
15#@return  str_arch - Arquitectura (i386 para 32 bits, x86_64 para 64 bits).
16#@version 0.9.2 - Primera versión para OpenGnSys.
17#@author  Ramon Gomez, ETSII Universidad de Sevilla
18#@date    2010-07-17
19#*/
20function ogGetArch ()
21{
22if [ "$*" == "help" ]; then
23    ogHelp "$FUNCNAME" "$FUNCNAME" "$FUNCNAME  =>  x86_64"
24    return
25fi
26
27[ -d /lib64 ] && echo "x86_64" || echo "i386"
28}
29
30
31#/**
32#         ogGetOsType int_ndisk int_npartition
33#@brief   Devuelve el tipo del sistema operativo instalado.
34#@param   int_ndisk      nº de orden del disco
35#@param   int_npartition nº de orden de la partición
36#@return  OSType - Tipo de sistema operativo.
37#@see     ogGetOsVersion
38#*/ ##
39function ogGetOsType ()
40{
41# Si se solicita, mostrar ayuda.
42if [ "$*" == "help" ]; then
43    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
44           "$FUNCNAME 1 2  =>  Linux"
45    return
46fi
47ogGetOsVersion "$@" | cut -sf1 -d:
48}
49
50
51#/**
52#         ogGetOsVersion int_ndisk int_nfilesys
53#@brief   Devuelve la versión del sistema operativo instalado en un sistema de archivos.
54#@param   int_ndisk      nº de orden del disco
55#@param   int_nfilesys   nº de orden de la partición
56#@return  OSType:OSVersion - tipo y versión del sistema operativo.
57#@note    OSType = { Android, BSD, GrubLoader, Hurd, Linux, MacOS, Solaris, Windows, WinLoader }
58#@note    Requisitos: awk, head, chroot
59#@exception OG_ERR_FORMAT    Formato incorrecto.
60#@exception OG_ERR_NOTFOUND  Disco o partición no corresponden con un dispositiv
61#@exception OG_ERR_PARTITION Fallo al montar el sistema de archivos.
62#@version 0.9 - Primera versión para OpenGnSys
63#@author  Ramon Gomez, ETSII Universidad de Sevilla
64#@date    2009-09-15
65#@version 1.0.4 - Incluir tipos BSD, MacOS y Solaris.
66#@author  Ramon Gomez, ETSII Universidad de Sevilla
67#@date    2012-06-29
68#@version 1.0.5 - Incluir tipos GrubLoader, Hurd y WinLoader, leer por defecto fichero /etc/os-release.
69#@author  Ramon Gomez, ETSII Universidad de Sevilla
70#@date    2013-10-07
71#@version 1.0.6 - Detectar GrubLoader al final y sistemas basados en EFI.
72#@author  Ramon Gomez, ETSII Universidad de Sevilla
73#@date    2014-08-27
74#*/ ##
75function ogGetOsVersion ()
76{
77# Variables locales.
78local MNTDIR TYPE DISTRIB VERSION IS64BIT FILE
79# Si se solicita, mostrar ayuda.
80if [ "$*" == "help" ]; then
81    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
82           "$FUNCNAME 1 2  =>  Linux:Ubuntu precise (12.04 LTS) 64 bits"
83    return
84fi
85# Error si no se reciben 2 parametros.
86[ $# = 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
87
88# Montar la particion, si no lo estaba previamente.
89MNTDIR=$(ogMount $1 $2) || return $?
90
91# Buscar tipo de sistema operativo.
92# Para GNU/Linux: leer descripción.
93TYPE="Linux"
94FILE="$MNTDIR/etc/os-release"
95[ -r $FILE ] && VERSION="$(awk -F= '$1~/PRETTY_NAME/ {gsub(/\"/,"",$2); print $2}' $FILE)"
96# Si no se puede obtener, buscar en ficheros del sistema.
97if [ -z "$VERSION" ]; then
98    FILE="$MNTDIR/etc/lsb-release"
99    [ -r $FILE ] && VERSION="$(awk -F= '$1~/DESCRIPTION/ {gsub(/\"/,"",$2); print $2}' $FILE)"
100    for DISTRIB in redhat SuSE mandrake gentoo; do
101        FILE="$MNTDIR/etc/${DISTRIB}-release"
102        [ -r $FILE ] && VERSION="$(head -1 $FILE)"
103    done
104    FILE="$MNTDIR/etc/arch-release"
105    [ -r $FILE ] && VERSION="Arch Linux"
106    FILE="$MNTDIR/etc/slackware-version"
107    [ -r $FILE ] && VERSION="Slackware $(cat $FILE)"
108fi
109# Si no se encuentra, intentar ejecutar "lsb_release".
110[ -z "$VERSION" ] && VERSION=$(chroot $MNTDIR lsb_release -d 2>/dev/null | awk -F":\t" '{print $2}')
111# Comprobar Linux de 64 bits.
112[ -n "$VERSION" ] && [ -e $MNTDIR/lib64 ] && IS64BIT="$MSG_64BIT"
113# Para Android, leer fichero de propiedades.
114if [ -z "$VERSION" ]; then
115    TYPE="Android"
116    FILE="$MNTDIR/android*/system/build.prop"
117    [ -r $FILE ] && VERSION="Android $(awk -F= '$1~/(product.brand|build.version.release)/ {print $2}' $FILE | tr '\n' ' ')"
118    [ -e $MNTDIR/lib64 ] && IS64BIT="$MSG_64BIT"
119fi
120# Para GNU/Hurd, comprobar fichero de inicio (basado en os-prober).
121if [ -z "$VERSION" ]; then
122    TYPE="Hurd"
123    FILE="$MNTDIR/hurd/init"
124    [ -r $FILE ] && VERSION="GNU/Hurd"
125fi
126# Para Windows: leer la version del registro.
127if [ -z "$VERSION" ]; then
128    TYPE="Windows"
129    VERSION=$(ogGetRegistryValue $MNTDIR software '\Microsoft\Windows NT\CurrentVersion\ProductName' 2>/dev/null)
130    [ -n "$(ogGetRegistryValue $MNTDIR software '\Microsoft\Windows\CurrentVersion\ProgramW6432Dir' 2>/dev/null)" ] && IS64BIT="$MSG_64BIT"
131fi
132# Para cargador Windows: buscar versión en fichero BCD (basado en os-prober).
133if [ -z "$VERSION" ]; then
134    TYPE="WinLoader"
135    FILE="$(ogGetPath $MNTDIR/boot/bcd)"
136    [ -z "$FILE" ] && FILE="$(ogGetPath $MNTDIR/EFI/Microsoft/boot/bcd)"
137    if [ -n "$FILE" ]; then
138        for DISTRIB in "Windows Recovery" "Windows Boot"; do
139            if grep -qs "$(echo "$DISTRIB" | sed 's/./&./g')" $FILE; then
140                VERSION="$DISTRIB loader"
141            fi
142        done
143    fi
144fi
145# Para MacOS: detectar kernel y completar con fichero plist de información del sistema.
146if [ -z "$VERSION" ]; then
147    TYPE="MacOS"
148    # Kernel de Mac OS (no debe ser fichero de texto).
149    FILE="$MNTDIR/mach_kernel"
150    if [ -z "$(file -b $FILE | grep 'text')" ]; then
151        # Obtener tipo de kernel.
152        [ -n "$(file -b $FILE | grep 'Mach-O')" ] && VERSION="Mac OS"
153        [ -n "$(file -b $FILE | grep 'Mach-O 64-bit')" ] && IS64BIT="$MSG_64BIT"
154        # Datos de configuración de versión de Mac OS.
155        FILE="$MNTDIR/System/Library/CoreServices/SystemVersion.plist"
156        [ -r $FILE ] && VERSION=$(awk -F"[<>]" '
157                                      /ProductName/ {getline;s=$3}
158                                      /ProductVersion/ {getline;v=$3}
159                                      END {print s,v}' $FILE)
160        # Datos de recuperación de Mac OS.
161        FILE="$MNTDIR/com.apple.recovery.boot"
162        [ -r $FILE -a -n "$VERSION" ] && VERSION="$VERSION recovery"
163    fi
164fi
165# Para FreeBSD: obtener datos del Kernel.
166### TODO Revisar solución.
167if [ -z "$VERSION" ]; then
168    TYPE="BSD"
169    FILE="$MNTDIR/boot/kernel/kernel"
170    if [ -r $FILE ]; then
171        VERSION="$(strings $FILE|awk '/@.*RELEASE/ {print $1,$2}')"
172        [ -n "$(file -b $FILE | grep 'x86-64')" ] && IS64BIT="$MSG_64BIT"
173    fi
174fi
175# Para Solaris: leer el fichero de versión.
176### TODO Revisar solución.
177if [ -z "$VERSION" ]; then
178    TYPE="Solaris"
179    FILE="$MNTDIR/etc/release"
180    [ -r $FILE ] && VERSION="$(head -1 $FILE)"
181fi
182# Para cargador GRUB, comprobar fichero de configuración.
183if [ -z "$VERSION" ]; then
184    TYPE="GrubLoader"
185    for FILE in $MNTDIR/{,boot/}grub/menu.lst; do
186        [ -r $FILE ] && VERSION="GRUB Loader"
187    done
188    for FILE in $MNTDIR/{,boot/}{grub{,2},EFI/*}/grub.cfg; do
189        [ -r $FILE ] && VERSION="GRUB2 Loader"
190    done
191fi
192
193# Mostrar resultado y salir sin errores.
194[ -n "$VERSION" ] && echo "$TYPE:$VERSION $IS64BIT"
195return 0
196}
197
198
199#/**
200#         ogGetSerialNumber
201#@brief   Obtiene el nº de serie del cliente.
202#@version 1.1.0 - Primeras versión con OpenGnsys
203#@author  Ramon Gomez, ETSII Universidad de Sevilla
204#@date    2015-06-08
205function ogGetSerialNumber ()
206{
207# Si se solicita, mostrar ayuda.
208if [ "$*" == "help" ]; then
209    ogHelp "$FUNCNAME" "$FUNCNAME"
210    return
211fi
212
213# Obtener nº de serie (ignorar los no especificados)
214dmidecode -s system-serial-number | egrep -vi "(not specified|filled by o.e.m.)"
215}
216
217
218#/**
219#         ogListHardwareInfo
220#@brief   Lista el inventario de hardware de la máquina cliente.
221#@return  TipoDispositivo:Modelo    (por determinar)
222#@warning Se ignoran los parámetros de entrada.
223#@note    TipoDispositivo = { bio, boa, bus, cha, cdr, cpu, dis, fir, mem, mod, mul, net, sto, usb, vga }
224#@note    Requisitos: dmidecode, lshw, awk
225#@version 0.1 - Primeras pruebas con OpenGnSys
226#@author  Ramon Gomez, ETSII Universidad de Sevilla
227#@date    2009-07-28
228#@version 1.1.0 - Incluir nuevos componentes al inventario.
229#@author  Ramon Gomez, ETSII Universidad de Sevilla
230#@date    2014-04-23
231#*/ ##
232function ogListHardwareInfo ()
233{
234# Si se solicita, mostrar ayuda.
235if [ "$*" == "help" ]; then
236    ogHelp "$FUNCNAME" "$FUNCNAME"
237    return
238fi
239
240# Recopilación de disposibivos procesando la salida de \c lshw
241ogEcho info "$MSG_HARDWAREINVENTORY}"
242echo "cha=$(dmidecode -s chassis-type)" | grep -v "Other"
243[ -e /sys/firmware/efi ] && echo "boo=UEFI" || echo "boo=BIOS"
244lshw | awk 'BEGIN {type="mod";}
245       /product:/ {sub(/ *product: */,"");  prod=$0;}
246       /vendor:/  {sub(/ *vendor: */,"");   vend=$0;}
247       /version:/ {sub(/ *version: */,"v.");vers=$0;}
248       /size:/    {size=$2;}
249       /clock:/   {clock=$2;}
250       /slot:/    {sub(/ *slot: */,"");     slot=$0;}
251       /\*-/      {if (type=="mem"){
252                     if (size!="")
253                       print type"="vend,prod,size,clock" ("slot")";
254                   }else{
255                     if (type!="" && prod!=""){
256                       if (prod=="v."vers)
257                         vers="";
258                       print type"="vend,prod,size,vers;} }
259                   type=prod=vend=vers=size=clock=slot="";}
260       $1~/-core/    {type="boa";}
261       $1~/-firmware/ {type="bio";}
262       $1~/-cpu/     {type="cpu";}
263       $1~/-bank/    {type="mem";}
264       $1~/-ide/     {type="ide";}
265       $1~/-storage/ {type="sto";}
266       $1~/-disk/    {type="dis";}
267       $1~/-cdrom/   {type="cdr";}
268       $1~/-display/ {type="vga";}
269       $1~/-network/ {type="net";}
270       $1~/-multimedia/ {type="mul";}
271       $1~/-usb/     {type="usb";}
272       $1~/-firewire/ {type="fir";}
273       $1~/-serial/  {type="bus";}
274       END           {if (type!="" && prod!="")
275                        print type"="vend,prod,size,vers;}
276      '
277# */ (comentario para Doxygen)
278}
279
280
281#/**
282#         ogListSoftware int_ndisk int_npartition
283#@brief   Lista el inventario de software instalado en un sistema operativo.
284#@param   int_ndisk      nº de orden del disco
285#@param   int_npartition nº de orden de la partición
286#@return  programa versión ...
287#@warning Se ignoran los parámetros de entrada.
288#@note    Requisitos: ...
289#@todo    Detectar software en Linux
290#@version 0.1 - Primeras pruebas con OpenGnSys
291#@author  Ramon Gomez, ETSII Universidad de Sevilla
292#@date    2009-09-23
293#@version 1.0.5 - Aproximación para inventario de software de Mac OS.
294#@author  Ramon Gomez, ETSII Universidad de Sevilla
295#@date    2013-10-08
296#@version 1.0.6 - Proceso depende del tipo de SO y sporte para FreeBSD.
297#@author  Ramon Gomez, ETSII Universidad de Sevilla
298#@date    2014-11-13
299#*/ ##
300function ogListSoftware ()
301{
302# Variables locales.
303local MNTDIR TYPE DPKGDIR RPMDIR PACMANDIR KEYS KEYS32 k PROG VERS
304
305# Si se solicita, mostrar ayuda.
306if [ "$*" == "help" ]; then
307    ogHelp "$FUNCNAME" "$FUNCNAME 1 1"
308    return
309fi
310# Error si no se reciben 2 parametros.
311[ $# = 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
312
313# Obtener tipo de sistema de archivos y montarlo.
314MNTDIR=$(ogMount $1 $2) || return $?
315TYPE=$(ogGetOsType $1 $2) || return $?
316
317case "$TYPE" in
318    Linux)          # Software de GNU/Linux.
319        # Procesar paquetes dpkg.
320        DPKGDIR="${MNTDIR}/var/lib/dpkg"
321        if [ -r $DPKGDIR ]; then
322            # Proceso de fichero en sistemas de 64 bits.
323            awk '/Package:/ {if (pack!="") print pack,vers;
324                             sub(/-dev$/,"",$2);
325                             pack=$2}
326                 /Version:/ {sub(/^.*:/,"",$2); sub(/-.*$/,"",$2);
327                             vers=$2}
328                 /Status:/  {if ($2!="install") pack=vers=""}
329                 END        {if (pack!="") print pack,vers}
330                ' $DPKGDIR/status | sort | uniq
331        fi
332        # Procesar paquetes RPM.
333        RPMDIR="${MNTDIR}/var/lib/rpm"
334        if [ -r $RPMDIR ]; then
335            # Listar si está instalado el paquete "rpm" en el cliente.
336            if which rpm &>/dev/null; then
337                rm -f ${RPMDIR}/__db.*
338                rpm --dbpath $RPMDIR -qa --qf "%{NAME} %{VERSION}\n" 2>/dev/null | \
339                    awk '$1!~/-devel$/ {sub(/-.*$/,"",$2); print $0}' | sort | uniq
340                rm -f ${RPMDIR}/__db.*
341            else
342                # Obtener el nombre de cada paquete en la BD de RPM.
343                python <<<"
344import re;
345import bsddb;
346db=bsddb.hashopen('$RPMDIR/Name','r');
347for k in db.keys():
348    print re.sub('-devel$','',k);" | sort | uniq
349            fi
350        fi
351        # Procesar paquetes pacman.
352        PACMANDIR="${MNTDIR}/var/lib/pacman/local"
353        if [ -r $PACMANDIR ]; then
354            # FIXME Separar nombre y versión de los paquetes
355            ls -A $PACMANDIR
356        fi
357        ;;
358    Windows)        # Software de Windows.
359        # Claves de registro para programas instalados: formato "{clave}".
360        KEYS=$(ogListRegistryKeys $MNTDIR software '\Microsoft\Windows\CurrentVersion\Uninstall')
361        KEYS32=$(ogListRegistryKeys $MNTDIR software '\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall')
362        # Mostrar los valores "DisplayName" y "DisplayVersion" para cada clave.
363        (for k in $KEYS; do
364            PROG=$(ogGetRegistryValue $MNTDIR software "\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayName")
365            if [ -n "$PROG" ]; then
366                VERS=$(ogGetRegistryValue $MNTDIR software "\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayVersion")
367                echo "$PROG $VERS"
368            fi
369        done
370        for k in $KEYS32; do
371            PROG=$(ogGetRegistryValue $MNTDIR software "\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayName")
372            if [ -n "$PROG" ]; then
373                VERS=$(ogGetRegistryValue $MNTDIR software "\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayVersion")
374                echo "$PROG $VERS"
375            fi
376        done) | sort | uniq
377        ;;
378    MacOS)          # Software de Mac OS.
379        # Listar directorios de aplicaciones e intentar obtener la versión del fichero .plist (tanto original como descomprimido).
380        find "${MNTDIR}/Applications" -type d -name "*.app" -prune -print | \
381                while read k; do
382                    FILE="$k/Contents/version.plist"
383                    [ -s "$FILE" ] || FILE="$k/Contents/version.plist.uncompress"
384                    [ -s "$FILE" ] && VERSION=$(awk -F"[<>]" '/ShortVersionString/ {getline;v=$3}
385                                                              END {print v}' "$FILE")
386                    echo "$(basename "$k" .app) $VERSION"
387                done | sort
388        ;;
389    BSD)            # Software de FreeBSD.
390        sqlite3 $MNTDIR/var/db/pkg/local.sqlite <<<"SELECT name FROM pkg_search;" 2>/dev/null | \
391                sed 's/\(.*\)-\(.*\)/\1 \2/g' | sort
392        ;;
393    *)  ogRaiseError $OG_ERR_PARTITION "$1, $2"
394        return $? ;;
395esac
396}
397
398
399#/**  @function ogInfoCache: @brief muestra la informacion de la CACHE.
400#@param  sin parametros
401#@return  texto que se almacena en $IP.-InfoCache.  punto_montaje, tama?oTotal, TamanioOcupado, TaminioLibre, imagenes dentro de la cahce
402#@warning  Salidas de errores no determinada
403#@warning   printf no soportado por busybox
404#@attention
405#@version 0.1   Date: 27/10/2008 Author Antonio J. Doblas Viso. Universidad de Malaga
406#*/
407function ogInfoCache ()
408{
409local info infoFilesystem infoSize infoUsed infoUsedPorcet infoMountedOn content
410if ogMountCache
411then
412        info=`df -h | grep $OGCAC`
413        infoFilesystem=`echo $info | cut -f1 -d" "`
414        infoSize=`echo $info | cut -f2 -d" "`
415        infoUsed=`echo $info | cut -f3 -d" "`
416        infoAvail=`echo $info | cut -f4 -d" "`
417        infoUsedPorcet=`echo $info | cut -f5 -d" "`
418        infoMountedOn=`echo $info | cut -f2 -d" "`
419        if `ls  ${OGCAC}$OGIMG > /dev/null 2>&1`
420        then
421               cd ${OGCAC}${OPENGNSYS}
422                #content=`find images/ -type f -printf "%h/  %f  %s \n"`   busybox no soporta printf
423                content=`find images/ -type f`
424                cd /
425                echo $info
426                echo -ne $content
427                echo " "
428                #echo "$info" > ${OGLOG}/${IP}-InfoCache
429                #echo "$content" >> {$OGLOG}/${IP}-InfoCache
430        else
431                echo $info
432                #echo "$info" > {$OGLOG}/${IP}-InfoCache
433        fi
434        ogUnmountCache
435else
436        echo " "
437        #echo " " > {$OGLOG}/${IP}-InfoCache
438
439fi
440}
441
Note: See TracBrowser for help on using the repository browser.