source: client/engine/Inventory.lib @ a6d6d6f

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 a6d6d6f was aaf5f9f, checked in by irina <irinagomez@…>, 9 years ago

#713 ogListHardwareInfo: Si no existen varios bancos de memoria muestra la memoria total del sistema. ogAdmBD.sql: se corrige errata en los iconos de inventario

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

  • Property mode set to 100755
File size: 16.8 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                       print type"="vend,prod,size,clock" ("slot")";
296                   }else{
297                     if (type!="" && prod!=""){
298                       if (prod=="v."vers)
299                         vers="";
300                       print type"="vend,prod,size,vers;} }
301                   if (type=="totalmem") {
302                        totalmemory="mem="size;
303                   }
304                   type=prod=vend=vers=size=clock=slot="";}
305       $1~/-core/    {type="boa";}
306       $1~/-firmware/ {type="bio";}
307       $1~/-cpu/     {type="cpu";}
308       $1~/-bank/    {type="mem";}
309       $1~/-memory/  {type="totalmem";}
310       $1~/-ide/     {type="ide";}
311       $1~/-storage/ {type="sto";}
312       $1~/-disk/    {type="dis";}
313       $1~/-cdrom/   {type="cdr";}
314       $1~/-display/ {type="vga";}
315       $1~/-network/ {type="net";}
316       $1~/-multimedia/ {type="mul";}
317       $1~/-usb/     {type="usb";}
318       $1~/-firewire/ {type="fir";}
319       $1~/-serial/  {type="bus";}
320       END           {if (type!="" && prod!="")
321                        print type"="vend,prod,size,vers;
322                      if ( length(numbank) == 0 && length(totalmemory) >=4 )
323                        print totalmemory; }
324      '
325# */ (comentario para Doxygen)
326}
327
328
329#/**
330#         ogListSoftware int_ndisk int_npartition
331#@brief   Lista el inventario de software instalado en un sistema operativo.
332#@param   int_ndisk      nº de orden del disco
333#@param   int_npartition nº de orden de la partición
334#@return  programa versión ...
335#@warning Se ignoran los parámetros de entrada.
336#@note    Requisitos: ...
337#@todo    Detectar software en Linux
338#@version 0.1 - Primeras pruebas con OpenGnSys
339#@author  Ramon Gomez, ETSII Universidad de Sevilla
340#@date    2009-09-23
341#@version 1.0.5 - Aproximación para inventario de software de Mac OS.
342#@author  Ramon Gomez, ETSII Universidad de Sevilla
343#@date    2013-10-08
344#@version 1.0.6 - Proceso depende del tipo de SO y soporte para FreeBSD.
345#@author  Ramon Gomez, ETSII Universidad de Sevilla
346#@date    2014-11-13
347#@version 1.1.0 - Se muestra el sistema operativo en la primera línea de la salida
348#@author  Irina Gomez, ETSII Universidad de Sevilla
349#@date    2016-04-26
350#*/ ##
351function ogListSoftware ()
352{
353# Variables locales.
354local MNTDIR TYPE DPKGDIR RPMDIR PACMANDIR KEYS KEYS32 k PROG VERS
355
356# Si se solicita, mostrar ayuda.
357if [ "$*" == "help" ]; then
358    ogHelp "$FUNCNAME" "$FUNCNAME 1 1"
359    return
360fi
361# Error si no se reciben 2 parametros.
362[ $# = 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
363
364# Obtener tipo de sistema de archivos y montarlo.
365MNTDIR=$(ogMount $1 $2) || return $?
366TYPE=$(ogGetOsType $1 $2) || return $?
367
368# Sistema Operativo en la primera línea de la salida
369ogGetOsVersion $1 $2 | awk -F ':'  '{print $2}'
370
371case "$TYPE" in
372    Linux)          # Software de GNU/Linux.
373        # Procesar paquetes dpkg.
374        DPKGDIR="${MNTDIR}/var/lib/dpkg"
375        if [ -r $DPKGDIR ]; then
376            # Proceso de fichero en sistemas de 64 bits.
377            awk '/Package:/ {if (pack!="") print pack,vers;
378                             sub(/-dev$/,"",$2);
379                             pack=$2}
380                 /Version:/ {sub(/^.*:/,"",$2); sub(/-.*$/,"",$2);
381                             vers=$2}
382                 /Status:/  {if ($2!="install") pack=vers=""}
383                 END        {if (pack!="") print pack,vers}
384                ' $DPKGDIR/status | sort | uniq
385        fi
386        # Procesar paquetes RPM.
387        RPMDIR="${MNTDIR}/var/lib/rpm"
388        if [ -r $RPMDIR ]; then
389            # Listar si está instalado el paquete "rpm" en el cliente.
390            if which rpm &>/dev/null; then
391                rm -f ${RPMDIR}/__db.*
392                rpm --dbpath $RPMDIR -qa --qf "%{NAME} %{VERSION}\n" 2>/dev/null | \
393                    awk '$1!~/-devel$/ {sub(/-.*$/,"",$2); print $0}' | sort | uniq
394                rm -f ${RPMDIR}/__db.*
395            else
396                # Obtener el nombre de cada paquete en la BD de RPM.
397                python <<<"
398import re;
399import bsddb;
400db=bsddb.hashopen('$RPMDIR/Name','r');
401for k in db.keys():
402    print re.sub('-devel$','',k);" | sort | uniq
403            fi
404        fi
405        # Procesar paquetes pacman.
406        PACMANDIR="${MNTDIR}/var/lib/pacman/local"
407        if [ -r $PACMANDIR ]; then
408            ls $PACMANDIR | awk -F- '/-/ {print gensub(/-/, " ", NF-2);}'
409        fi
410        ;;
411    Windows)        # Software de Windows.
412        # Claves de registro para programas instalados: formato "{clave}".
413        KEYS=$(ogListRegistryKeys $MNTDIR software '\Microsoft\Windows\CurrentVersion\Uninstall')
414        KEYS32=$(ogListRegistryKeys $MNTDIR software '\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall')
415        # Mostrar los valores "DisplayName" y "DisplayVersion" para cada clave.
416        (for k in $KEYS; do
417            PROG=$(ogGetRegistryValue $MNTDIR software "\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayName")
418            if [ -n "$PROG" ]; then
419                VERS=$(ogGetRegistryValue $MNTDIR software "\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayVersion")
420                echo "$PROG $VERS"
421            fi
422        done
423        for k in $KEYS32; do
424            PROG=$(ogGetRegistryValue $MNTDIR software "\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayName")
425            if [ -n "$PROG" ]; then
426                VERS=$(ogGetRegistryValue $MNTDIR software "\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayVersion")
427                echo "$PROG $VERS"
428            fi
429        done) | sort | uniq
430        ;;
431    MacOS)          # Software de Mac OS.
432        # Listar directorios de aplicaciones e intentar obtener la versión del fichero .plist (tanto original como descomprimido).
433        find "${MNTDIR}/Applications" -type d -name "*.app" -prune -print | \
434                while read k; do
435                    FILE="$k/Contents/version.plist"
436                    [ -s "$FILE" ] || FILE="$k/Contents/version.plist.uncompress"
437                    [ -s "$FILE" ] && VERSION=$(awk -F"[<>]" '/ShortVersionString/ {getline;v=$3}
438                                                              END {print v}' "$FILE")
439                    echo "$(basename "$k" .app) $VERSION"
440                done | sort
441        ;;
442    BSD)            # Software de FreeBSD.
443        sqlite3 $MNTDIR/var/db/pkg/local.sqlite <<<"SELECT name FROM pkg_search;" 2>/dev/null | \
444                sed 's/\(.*\)-\(.*\)/\1 \2/g' | sort
445        ;;
446    *)  ogRaiseError $OG_ERR_PARTITION "$1, $2"
447        return $? ;;
448esac
449}
Note: See TracBrowser for help on using the repository browser.