OpenGnsys  1.1.1
Inventory.lib
Ir a la documentación de este archivo.
1 #!/bin/bash
2 #
12 #
20 function ogGetArch ()
21 {
22 if [ "$*" == "help" ]; then
23  ogHelp "$FUNCNAME" "$FUNCNAME" "$FUNCNAME => x86_64"
24  return
25 fi
26 
27 [ -d /lib64 ] && echo "x86_64" || echo "i386"
28 }
29 
30 
31 # ##
39 function ogGetOsType ()
40 {
41 # Si se solicita, mostrar ayuda.
42 if [ "$*" == "help" ]; then
43  ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \
44  "$FUNCNAME 1 2 => Linux"
45  return
46 fi
47 ogGetOsVersion "$@" | cut -sf1 -d:
48 }
49 
50 
51 # ##
63 function ogGetOsUuid ()
64 {
65 # Variables locales.
66 local MNTDIR
67 # Si se solicita, mostrar ayuda.
68 if [ "$*" == "help" ]; then
69  ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
70  "$FUNCNAME 1 2 => 540e47c6-8e78-4178-aa46-042e4803fb16"
71  return
72 fi
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.
77 MNTDIR=$(ogMount $1 $2) || return $?
78 
79 # Obtener UUID según el tipo de sistema operativo.
80 case "$(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  ;;
89 esac
90 }
91 
92 
93 # ##
100 function ogGetSerialNumber ()
101 {
102 # Variables locales.
103 local SERIALNO
104 # Si se solicita, mostrar ayuda.
105 if [ "$*" == "help" ]; then
106  ogHelp "$FUNCNAME" "$FUNCNAME" "$FUNCNAME => 123456"
107  return
108 fi
109 
110 # Obtener nº de serie (ignorar los no especificados).
111 SERIALNO=$(dmidecode -s system-serial-number | egrep -vi "(^[ 0]+$|not specified|to be filled|invalid entry|default string)")
112 # Quitar espacios y truncar cadena si >25 caracteres.
113 SERIALNO="${SERIALNO// /}"
114 [ ${#SERIALNO} -gt 25 ] && SERIALNO="${SERIALNO:0:22}..."
115 [ -n "$SERIALNO" ] && echo "$SERIALNO"
116 return 0
117 }
118 
119 
120 # ##
124 function ogIsEfiActive ()
125 {
126 test -d /sys/firmware/efi
127 }
128 
129 
130 # ##
145 {
146 # Si se solicita, mostrar ayuda.
147 if [ "$*" == "help" ]; then
148  ogHelp "$FUNCNAME" "$FUNCNAME"
149  return
150 fi
151 
152 # Recopilación de dispositivos procesando la salida de \c lshw
153 ogEcho info "$MSG_HARDWAREINVENTORY}"
154 echo "cha=$(dmidecode -s chassis-type)" | grep -v "Other"
155 [ -e /sys/firmware/efi ] && echo "boo=UEFI" || echo "boo=BIOS"
156 lshw | awk 'BEGIN {type="mod";}
157  /product:/ {sub(/ *product: */,""); prod=$0;}
158  /vendor:/ {sub(/ *vendor: */,""); vend=$0;}
159  /version:/ {sub(/ *version: */,"v.");vers=$0;}
160  /size:/ {size=$2;}
161  /clock:/ {clock=$2;}
162  /slot:/ {sub(/ *slot: */,""); slot=$0;}
163  /\*-/ {if (type=="mem"){
164  if (size!=""){
165  numbank++;
166  print type"="vend,prod,size,clock" ("slot")";}
167  }else{
168  if (type=="totalmem"){
169  if (size!=""){
170  totalmemory="mem="size;}
171  }else{
172  if (type!="" && prod!=""){
173  if (prod=="v."vers)
174  vers="";
175  print type"="vend,prod,size,vers;} }
176  }
177  type=prod=vend=vers=size=clock=slot="";}
178  $1~/-core/ {type="boa";}
179  $1~/-firmware/ {type="bio";}
180  $1~/-cpu/ {type="cpu";}
181  $1~/-bank/ {type="mem";}
182  $1~/-memory/ {type="totalmem";}
183  $1~/-ide/ {type="ide";}
184  $1~/-storage/ {type="sto";}
185  $1~/-disk/ {type="dis";}
186  $1~/-cdrom/ {type="cdr";}
187  $1~/-display/ {type="vga";}
188  $1~/-network/ {type="net";}
189  $1~/-multimedia/ {type="mul";}
190  $1~/-usb/ {type="usb";}
191  $1~/-firewire/ {type="fir";}
192  $1~/-serial/ {type="bus";}
193  END {if (type!="" && prod!="")
194  print type"="vend,prod,size,vers;
195  if (length(numbank)==0 && length(totalmemory)>=4)
196  print totalmemory; }
197  '
198 # */ (comentario para Doxygen)
199 }
200 
201 
202 # ##
224 function ogListSoftware ()
225 {
226 # Variables locales.
227 local APPS HIVE k KEYS KEYS32 MNTDIR PKGDIR PROG VERS TMPFILE TYPE
228 
229 # Si se solicita, mostrar ayuda.
230 if [ "$*" == "help" ]; then
231  ogHelp "$FUNCNAME" "$FUNCNAME 1 1"
232  return
233 fi
234 # Error si no se reciben 2 parametros.
235 [ $# = 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
236 
237 # Obtener tipo de sistema de archivos y montarlo.
238 MNTDIR=$(ogMount $1 $2) || return $?
239 TYPE=$(ogGetOsType $1 $2) || return $?
240 
241 # Ficheros temporales.
242 APPS=$(mktemp /tmp/apps.XXXXX)
243 TMPFILE=$(mktemp /tmp/tmp.XXXXX)
244 trap "rm -f $APPS $TMPFILE" 1 2 3 9 15
245 
246 case "$TYPE" in
247  Linux) # Software de GNU/Linux.
248  # Procesar paquetes dpkg.
249  PKGDIR="${MNTDIR}/var/lib/dpkg"
250  if [ -r $PKGDIR ]; then
251  # Proceso de fichero en sistemas de 64 bits.
252  awk '/Package:/ {if (pack!="") print pack,vers;
253  sub(/-dev$/,"",$2);
254  pack=$2}
255  /Version:/ {sub(/^.*:/,"",$2); sub(/-.*$/,"",$2);
256  vers=$2}
257  /Status:/ {if ($2!="install") pack=vers=""}
258  END {if (pack!="") print pack,vers}
259  ' $PKGDIR/status > $APPS
260  fi
261  # Procesar paquetes RPM.
262  PKGDIR="${MNTDIR}/var/lib/rpm"
263  if [ -r $PKGDIR ]; then
264  # Listar si está instalado el paquete "rpm" en el cliente.
265  if which rpm &>/dev/null; then
266  rm -f ${PKGDIR}/__db.*
267  rpm --dbpath $PKGDIR -qa --qf "%{NAME} %{VERSION}\n" 2>/dev/null | \
268  awk '$1!~/-devel$/ {sub(/-.*$/,"",$2); print $0}' > $APPS
269  rm -f ${PKGDIR}/__db.*
270  else
271  # Obtener el nombre de cada paquete en la BD de RPM.
272  python <<<"
273 import re;
274 import bsddb;
275 db=bsddb.hashopen('$PKGDIR/Name','r');
276 for k in db.keys():
277  print re.sub('-devel$','',k);" > $APPS
278  fi
279  fi
280  # Procesar paquetes pacman.
281  PKGDIR="${MNTDIR}/var/lib/pacman/local"
282  if [ -r $PKGDIR ]; then
283  ls $PKGDIR | awk -F- '/-/ {print gensub(/-/, " ", NF-2);}' > $APPS
284  fi
285  # Procesar aplicaciones Snappy.
286  PKGDIR="${MNTDIR}/snap"
287  find $PKGDIR/*/current/meta -name snap.yaml -exec \
288  awk '/name:/ {pack=$2}
289  /version:/ {vers=$2}
290  END {if (pack!="") print pack,"(snap)",vers}' {} 2>/dev/null \; >> $APPS
291  # Procesar aplicaciones Flatpak.
292  PKGDIR="${MNTDIR}/var/lib/flatpak"
293  ls -1 $PKGDIR/app/*/current/active/deploy 2> /dev/null | python -c "
294 import sys
295 for f in sys.stdin:
296  p = open(f.strip()).read().split('\0')
297  try:
298  if(p[0] != 'flathub'):
299  raise ValueError
300  print('{} (flatpak) {}'.format(p[p.index('appdata-name') + 4], p[p.index('appdata-version') + 1]))
301  except ValueError:
302  pass
303 " >> $APPS
304  ;;
305  Windows) # Software de Windows.
306  # Comprobar tipo de proceso del registro de Windows.
307  if which hivexregedit &>/dev/null; then
308  # Nuevo proceso más rápido basado en "hivexregedit".
309  HIVE=$(ogGetHivePath $MNTDIR software 2>/dev/null)
310  if [ -n "$HIVE" ]; then
311  # Claves de registro para programas instalados.
312  hivexregedit --unsafe-printable-strings --export "$HIVE" '\Microsoft\Windows\CurrentVersion\Uninstall' > $TMPFILE 2>/dev/null
313  hivexregedit --unsafe-printable-strings --export "$HIVE" '\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall' >> $TMPFILE 2>/dev/null
314  # Mostrar los valores "DisplayName" y "DisplayVersion" para cada clave.
315  awk -F\" '$1~/^\[/ {n=""}
316  $2~/DisplayName/ {n=$4}
317  $2~/DisplayVersion/ {print n,$4}
318  ' $TMPFILE > $APPS
319  fi
320  else
321  # Compatibilidad con clientes ogLive antiguos.
322  # Claves de registro para programas instalados: formato "{clave}".
323  KEYS=$(ogListRegistryKeys $MNTDIR software '\Microsoft\Windows\CurrentVersion\Uninstall')
324  KEYS32=$(ogListRegistryKeys $MNTDIR software '\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall')
325  # Mostrar los valores "DisplayName" y "DisplayVersion" para cada clave.
326  for k in $KEYS; do
327  PROG=$(ogGetRegistryValue $MNTDIR software "\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayName")
328  if [ -n "$PROG" ]; then
329  VERS=$(ogGetRegistryValue $MNTDIR software "\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayVersion")
330  echo "$PROG $VERS"
331  fi
332  done > $APPS
333  for k in $KEYS32; do
334  PROG=$(ogGetRegistryValue $MNTDIR software "\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayName")
335  if [ -n "$PROG" ]; then
336  VERS=$(ogGetRegistryValue $MNTDIR software "\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayVersion")
337  echo "$PROG $VERS"
338  fi
339  done >> $APPS
340  fi
341  ;;
342  MacOS) # Software de Mac OS.
343  # Listar directorios de aplicaciones e intentar obtener la versión del fichero .plist (tanto original como descomprimido).
344  find "${MNTDIR}/Applications" -type d -name "*.app" -prune -print | \
345  while read k; do
346  FILE="$k/Contents/version.plist"
347  [ -s "$FILE" ] || FILE="$k/Contents/version.plist.uncompress"
348  [ -s "$FILE" ] && VERSION=$(awk -F"[<>]" '/ShortVersionString/ {getline;v=$3}
349  END {print v}' "$FILE")
350  echo "$(basename "$k" .app) $VERSION"
351  done > $APPS
352  ;;
353  BSD) # Software de FreeBSD.
354  sqlite3 $MNTDIR/var/db/pkg/local.sqlite <<<"SELECT name FROM pkg_search;" 2>/dev/null | \
355  sed 's/\(.*\)-\(.*\)/\1 \2/g' > $APPS
356  ;;
357  *) ogRaiseError $OG_ERR_NOTOS "$1, $2 ${TYPE+($TYPE)}"
358  return $? ;;
359 esac
360 
361 # Mostrar sistema Operativo y aplicaciones.
362 ogGetOsVersion $1 $2 | awk -F: '{print $2}'
363 sort $APPS | uniq | iconv -ct utf-8
364 rm -f $APPS $TMPFILE
365 }
366 
367 # ##
391 function ogGetOsVersion ()
392 {
393 # Variables locales.
394 local MNTDIR TYPE DISTRIB VERSION IS64BIT FILE
395 # Si se solicita, mostrar ayuda.
396 if [ "$*" == "help" ]; then
397  ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \
398  "$FUNCNAME 1 2 => Linux:Ubuntu precise (12.04 LTS) 64 bits"
399  return
400 fi
401 # Error si no se reciben 2 parametros.
402 [ $# = 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
403 
404 # Montar la particion, si no lo estaba previamente.
405 MNTDIR=$(ogMount $1 $2) || return $?
406 
407 # Buscar tipo de sistema operativo.
408 # Para GNU/Linux: leer descripción.
409 TYPE="Linux"
410 FILE="$MNTDIR/etc/os-release"
411 [ -r $FILE ] && VERSION="$(awk -F= '$1~/PRETTY_NAME/ {gsub(/"/,"",$2); print $2}' $FILE)"
412 # Si no se puede obtener, buscar en ficheros del sistema.
413 if [ -z "$VERSION" ]; then
414  FILE="$MNTDIR/etc/lsb-release"
415  [ -r $FILE ] && VERSION="$(awk -F= '$1~/DESCRIPTION/ {gsub(/"/,"",$2); print $2}' $FILE)"
416  for DISTRIB in redhat SuSE mandrake gentoo; do
417  FILE="$MNTDIR/etc/${DISTRIB}-release"
418  [ -r $FILE ] && VERSION="$(head -1 $FILE)"
419  done
420  FILE="$MNTDIR/etc/arch-release"
421  [ -r $FILE ] && VERSION="Arch Linux"
422  FILE="$MNTDIR/etc/slackware-version"
423  [ -r $FILE ] && VERSION="Slackware $(cat $FILE)"
424 fi
425 # Si no se encuentra, intentar ejecutar "lsb_release".
426 [ -z "$VERSION" ] && VERSION=$(chroot $MNTDIR lsb_release -d 2>/dev/null | awk -F":\t" '{print $2}')
427 # Comprobar Linux de 64 bits.
428 [ -n "$VERSION" ] && [ -e $MNTDIR/lib64 ] && IS64BIT="$MSG_64BIT"
429 # Para Android, leer fichero de propiedades.
430 if [ -z "$VERSION" ]; then
431  TYPE="Android"
432  FILE="$MNTDIR/android*/system/build.prop"
433  [ -r $FILE ] && VERSION="Android $(awk -F= '$1~/(product.brand|build.version.release)/ {print $2}' $FILE | tr '\n' ' ')"
434  [ -e $MNTDIR/lib64 ] && IS64BIT="$MSG_64BIT"
435 fi
436 # Para GNU/Hurd, comprobar fichero de inicio (basado en os-prober).
437 if [ -z "$VERSION" ]; then
438  TYPE="Hurd"
439  FILE="$MNTDIR/hurd/init"
440  [ -r $FILE ] && VERSION="GNU/Hurd"
441 fi
442 # Para Windows: leer la version del registro.
443 if [ -z "$VERSION" ]; then
444  TYPE="Windows"
445  FILE="$(ogGetHivePath $MNTDIR SOFTWARE)"
446  if [ -n "$FILE" ]; then
447  # Nuevo método más rápido para acceder al registro de Windows..
448  VERSION=$(echo $(hivexsh << EOT 2>/dev/null
449 load $FILE
450 cd \Microsoft\Windows NT\CurrentVersion
451 lsval ProductName
452 lsval ReleaseId
453 EOT
454  ))
455  [ -n "$(reglookup -H -p "Microsoft/Windows/CurrentVersion/ProgramW6432Dir" "$FILE" 2>/dev/null)" ] && IS64BIT="$MSG_64BIT"
456  if [ -z "$VERSION" ]; then
457  # Compatibilidad con métrodo antiguo y más lento de acceder al registro.
458  VERSION=$(ogGetRegistryValue $MNTDIR software '\Microsoft\Windows NT\CurrentVersion\ProductName' 2>/dev/null)
459  [ -n "$(ogGetRegistryValue $MNTDIR software '\Microsoft\Windows\CurrentVersion\ProgramW6432Dir' 2>/dev/null)" ] && IS64BIT="$MSG_64BIT"
460  fi
461  fi
462 fi
463 # Para cargador Windows: buscar versión en fichero BCD (basado en os-prober).
464 if [ -z "$VERSION" ]; then
465  TYPE="WinLoader"
466  FILE="$(ogGetPath $MNTDIR/boot/bcd)"
467  [ -z "$FILE" ] && FILE="$(ogGetPath $MNTDIR/EFI/Microsoft/boot/bcd)"
468  if [ -n "$FILE" ]; then
469  for DISTRIB in "Windows Recovery" "Windows Boot"; do
470  if grep -aqs "$(echo "$DISTRIB" | sed 's/./&./g')" $FILE; then
471  VERSION="$DISTRIB loader"
472  fi
473  done
474  fi
475 fi
476 # Para macOS: detectar kernel y completar con fichero plist de información del sistema.
477 if [ -z "$VERSION" ]; then
478  TYPE="MacOS"
479  # Kernel de Mac OS (no debe ser fichero de texto).
480  FILE="$MNTDIR/mach_kernel"
481  if [ -z "$(file -b $FILE | grep 'text')" ]; then
482  # Obtener tipo de kernel.
483  [ -n "$(file -b $FILE | grep 'Mach-O')" ] && VERSION="macOS"
484  [ -n "$(file -b $FILE | grep 'Mach-O 64-bit')" ] && IS64BIT="$MSG_64BIT"
485  # Datos de configuración de versión de Mac OS.
486  FILE="$MNTDIR/System/Library/CoreServices/SystemVersion.plist"
487  [ -r $FILE ] && VERSION=$(awk -F"[<>]" '
488  /ProductName/ {getline;s=$3}
489  /ProductVersion/ {getline;v=$3}
490  END {print s,v}' $FILE)
491  # Datos de recuperación de macOS.
492  FILE="$MNTDIR/com.apple.recovery.boot"
493  [ -r $FILE -a -n "$VERSION" ] && VERSION="$VERSION recovery"
494  fi
495 fi
496 # Para FreeBSD: obtener datos del Kernel.
497 ### TODO Revisar solución.
498 if [ -z "$VERSION" ]; then
499  TYPE="BSD"
500  FILE="$MNTDIR/boot/kernel/kernel"
501  if [ -r $FILE ]; then
502  VERSION="$(strings $FILE|awk '/@.*RELEASE/ {sub(/@\(#\)/,""); print $1,$2}')"
503  [ -n "$(file -b $FILE | grep 'x86-64')" ] && IS64BIT="$MSG_64BIT"
504  fi
505 fi
506 # Para Solaris: leer el fichero de versión.
507 ### TODO Revisar solución.
508 if [ -z "$VERSION" ]; then
509  TYPE="Solaris"
510  FILE="$MNTDIR/etc/release"
511  [ -r $FILE ] && VERSION="$(head -1 $FILE)"
512 fi
513 # Para cargador GRUB, comprobar fichero de configuración.
514 if [ -z "$VERSION" ]; then
515  TYPE="GrubLoader"
516  for FILE in $MNTDIR/{,boot/}grub/menu.lst; do
517  [ -r $FILE ] && VERSION="GRUB Loader"
518  done
519 #/* (comentario Doxygen)
520  for FILE in $MNTDIR/{,boot/}{grub{,2},EFI/*}/grub.cfg; do
521  [ -r $FILE ] && VERSION="GRUB2 Loader"
522  done
523 fi
524 #*/ (Comentario Doxygen)
525 # Mostrar resultado y salir sin errores.
526 [ -n "$VERSION" ] && echo "$TYPE:$VERSION $IS64BIT"
527 return 0
528 }
function ogGetHivePath()
Función básica que devuelve el camino del fichero con una sección del registro. #.
Definition: Registry.lib:221
function ogIsEfiActive()
Comprueba si el sistema tiene activo el arranque EFI.
Definition: Inventory.lib:124
Funciones para arranque y post-configuración de sistemas de archivos. #.
function ogRaiseError()
Devuelve el mensaje y el código de error correspondiente. #.
Definition: System.lib:188
function ogHelp()
Muestra mensaje de ayuda para una función determinda. #.
Definition: System.lib:153
Funciones básicas del sistema. #.
function lshw()
Definition: ToolsGNU.c:113
function ogGetPath()
Inicia el proceso de arranque de un sistema de archivos. #.
Definition: File.lib:237
function ogGetRegistryValue()
Devuelve el dato de un valor del registro de Windows. #.
Definition: Registry.lib:264
function ogListSoftware()
Lista el inventario de software instalado en un sistema operativo. #.
Definition: Inventory.lib:224
function ogGetOsType()
Devuelve el tipo del sistema operativo instalado. #.
Definition: Inventory.lib:39
function ogListHardwareInfo()
Lista el inventario de hardware de la máquina cliente. #.
Definition: Inventory.lib:144
function ogMount()
Definition: FileSystem.lib:704
function ogGetOsUuid()
Devuelve el UUID del sistema operativo instalado en un sistema de archivos. #.
Definition: Inventory.lib:63
function ogGetSerialNumber()
Obtiene el nº de serie del cliente. #.
Definition: Inventory.lib:100
function ms sys()
Definition: ToolsGNU.c:42
function ogEcho()
Muestra mensajes en consola y lo registra en fichero de incidencias. #.
Definition: System.lib:34
function awk()
Definition: ToolsGNU.c:89