source: client/engine/Inventory.lib @ ef5025f

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 ef5025f was 42d268a4, checked in by ramon <ramongomez@…>, 7 years ago

#730: Corregir errata al obtener bancos de memoria en inventario de hardware; crear fichero de comandos Windows si no existe al añadir el primero de ellos y subir el timeout de conexiones REST a 500 ms.

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

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