refs #1059 fix conflicts

pull/1/head
Natalia Serrano 2024-10-29 09:47:38 +01:00
commit d519113079
6 changed files with 98 additions and 96 deletions

View File

@ -1,20 +1,18 @@
import subprocess
import sys
def list_hardware_info():
# Replace this with the actual command to list hardware info
result = subprocess.run(['listHardwareInfo'], capture_output=True, text=True)
return result.stdout
def main(output_file):
# Ejecutar el comando `listHardwareInfo.py` y capturar el resultado
result = subprocess.run(["python3", "/opt/opengnsys/scripts/listHardwareInfo.py"], capture_output=True, text=True, check=True)
file_path = result.stdout.strip() # Obtener la ruta del archivo de salida de `listHardwareInfo.py`
def save_hardware_inventory(output_file):
hardware_info = list_hardware_info()
lines = hardware_info.splitlines()
if len(lines) > 1:
with open(output_file, 'w') as f:
f.write('\n'.join(lines[1:]))
# Leer desde la segunda línea del archivo y escribir en el archivo de salida especificado
with open(file_path, 'r') as input_file, open(output_file, 'w') as output:
lines = input_file.readlines()[1:] # Saltar la primera línea
output.writelines(lines)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python InventarioHardware.py <output_file>")
else:
save_hardware_inventory(sys.argv[1])
print("Uso: python3 InventarioHardware.py <archivo_salida>")
sys.exit(1)
main(sys.argv[1])

0
client/lib/engine/bin/FileLib.py 100644 → 100755
View File

91
client/lib/engine/bin/SystemLib.py 100644 → 100755
View File

@ -1,68 +1,52 @@
import subprocess
import datetime
from zoneinfo import ZoneInfo
import sys
import os
import shutil
import ogGlobals
from DiskLib import *
from CacheLib import *
from StringLib import *
print (">>>>>>>>>>>>>>>>>>>> Load ", __name__, " <<<<<<<<<<<<<<<<<<<<<<")
#from engine.DiskLib import *
#from engine.CacheLib import *
#from engine.StringLib import *
#NODEBUGFUNCTIONS, OGIMG, OG_ERR_CACHESIZE, OG_ERR_NOTCACHE, OG_ERR_NOTWRITE, OG_ERR_FILESYS
#OG_ERR_REPO, OG_ERR_NOTOS, OG_ERR_NOGPT, OG_ERR_OUTOFLIMIT, OG_ERR_IMAGE, OG_ERR_CACHE
#OGLOGSESSION, OGLOGCOMMAND, OGLOGFILE, OG_ERR_LOCKED, OG_ERR_PARTITION, OG_ERR_FORMAT, OG_ERR_NOTEXEC, OG_ERR_NOTFOUND
def _logtype2logfile (t):
if 'log' == t: return ogGlobals.OGLOGFILE
elif 'command' == t: return ogGlobals.OGLOGCOMMAND
elif 'session' == t: return ogGlobals.OGLOGSESSION
else: raise Exception (f'unknown log type ({t})')
#/**
# ogEcho [str_logtype ...] [str_loglevel] "str_message" ...
#@brief Muestra mensajes en consola y lo registra en fichero de incidencias.
#@param str_logtype tipo de registro de incidencias ("log", "command", "session")
#@param str_loglevel nivel de registro de incidencias ("info", "warning", "error")
#@param str_message mensaje (puede recibir más de 1 parámetro.
#@return Mensaje mostrado.
#*/
## zero or more logtypes can be specified
## zero or one loglevel can be specified
## ogEcho ([], None, msg)
## ogEcho ('log', None, msg)
## ogEcho ('session', None, msg)
## ogEcho (['log', 'session'], None, msg)
## ogEcho ([], None, 'info', msg)
## ogEcho ('log', None, 'info', msg)
## ogEcho ('session', None, 'info', msg)
## ogEcho (['log', 'session'], 'info', msg)
def ogEcho (logtypes, loglevel, msg):
logfiles = []
if type (logtypes) is list:
for l in logtypes:
logfiles.append (_logtype2logfile (l))
else: ## string
logfiles.append (_logtype2logfile (logtypes))
def ogEcho(*args):
# Variables locales
CONT = 1
LOGS = ""
LOGLEVEL = ""
DATETIME = ""
if loglevel is None or 'help' == loglevel:
if ogGlobals.DEBUG.lower() != "no":
logfiles.append (ogGlobals.OGLOGFILE)
for f in logfiles:
with open (f, 'a') as fd:
fd.write (msg + '\n')
return
# Selección de ficheros de registro de incidencias.
while CONT:
args = list(args)
arg = args.pop(0).lower()
if arg == "log":
LOGS += " " + OGLOGFILE
elif arg == "command":
LOGS += " " + OGLOGCOMMAND
elif arg == "session":
LOGS += " " + OGLOGSESSION
else:
CONT = 0
if 'info' == loglevel or 'warning' == loglevel or 'error' == loglevel:
DATETIME = datetime.datetime.now(ZoneInfo(ogGlobals.TZ)).strftime("%F %T %Z")
# Selección del nivel de registro (opcional).
arg = args.pop(0).lower()
if arg == "help":
pass
elif arg == "info" or arg == "warning" or arg == "error":
LOGLEVEL = arg
for f in logfiles:
with open (f, 'a') as fd:
fd.write (f"OpenGnsys {loglevel} {DATETIME} {msg}\n")
if LOGLEVEL:
DATETIME = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Registrar mensajes en fichero de log si la depuración no está desactivada.
if DEBUG.lower() != "no":
LOGS += " " + OGLOGFILE
subprocess.call(f"logger -t OpenGnsys {LOGLEVEL} {DATETIME} {' '.join(args)}", shell=True)
else:
raise Exception (f'unknown loglevel ({loglevel})')
print(' '.join(args))
def ogExecAndLog(*args):
# Variables locales
@ -326,5 +310,8 @@ def ogCheckProgram(*args):
return 0
def ogIsVirtualMachine():
output = subprocess.run (["dmidecode", "-s", "system-product-name"], capture_output=True, text=True).stdout
return "KVM" in output or "VirtualBox" in output
output = subprocess.check_output(["dmidecode", "-s", "system-product-name"]).decode("utf-8")
if "KVM" in output or "VirtualBox" in output:
return 1
else:
return 0

View File

View File

@ -1,6 +1,17 @@
#!/usr/bin/env python3
import subprocess
import sys
from NetLib import ogGetIpAddress
def get_ip_address(*args):
try:
# Ejecuta ogGetIpAddress como un comando en el sistema
result = subprocess.run(["/opt/opengnsys/client/lib/engine/bin/ogGetIpAddress"] + list(args),
capture_output=True, text=True, check=True)
print(result.stdout.strip())
except subprocess.CalledProcessError as e:
print(f"Error ejecutando ogGetIpAddress: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
args = sys.argv[1:]
output = ogGetIpAddress(args)
print(output)
get_ip_address(*sys.argv[1:])

View File

@ -1,36 +1,42 @@
import os
import subprocess
import os
import sys
sys.path.append('/opt/opengnsys/lib/engine/bin') # Agregar ruta de NetLib.py
from InventoryLib import ogListHardwareInfo
from NetLib import ogGetIpAddress
#!/usr/bin/env python3
def main():
PROG = os.path.basename(__file__)
if len(sys.argv) != 1:
og_raise_error(os.getenv('OG_ERR_FORMAT'), f"{os.getenv('MSG_FORMAT')}: {PROG}")
# Directory of the server where log files are exported
OGLOG = os.getenv('OGLOG')
SERVERLOGDIR = None
mount_output = subprocess.check_output(['mount']).decode('utf-8')
for line in mount_output.splitlines():
def get_server_log_dir():
# Obtener el directorio de logs del servidor
oglog = os.getenv("OGLOG")
if not oglog:
return ""
result = subprocess.run(["mount"], capture_output=True, text=True)
for line in result.stdout.splitlines():
parts = line.split()
if len(parts) > 3 and parts[3] == OGLOG:
SERVERLOGDIR = parts[1]
break
if len(parts) >= 4 and parts[3] == oglog:
return parts[1]
return ""
# List file: hard-IP
HARDFILE = f"hard-{og_get_ip_address()}"
# Redirect output to the list file
try:
with open(f"{OGLOG}/{HARDFILE}", 'w') as f:
f.write(og_list_hardware_info())
except Exception as e:
sys.exit(1)
def list_hardware_info():
oglog = os.getenv("OGLOG", "/tmp") # Usar /tmp como valor por defecto para OGLOG
# Output: path of the list file in the repository server
# print(f"{SERVERLOGDIR}/{HARDFILE}")
print(f"{OGLOG}/{HARDFILE}")
# Fichero de listado de hardware basado en la IP obtenida
hardfile = f"hard-{ogGetIpAddress()}"
# Ejecutar ogListHardwareInfo y redirigir al archivo de listado
hardware_info_path = os.path.join(oglog, hardfile)
with open(hardware_info_path, 'w') as output_file:
output_file.write(ogListHardwareInfo())
return hardware_info_path
if __name__ == "__main__":
main()
# Obtener el directorio del servidor donde se exportan los ficheros de registro
server_log_dir = get_server_log_dir()
# Generar el archivo de listado de hardware y obtener su ruta
hardware_info_path = list_hardware_info()
# Imprimir la ruta del archivo generado
print(hardware_info_path)