refs #1729 add interfaceAdm/getConfiguration.py

pull/8/head
Natalia Serrano 2025-03-19 13:16:07 +01:00
parent a5a0b2bdb7
commit 5d0f041759
1 changed files with 96 additions and 70 deletions

View File

@ -1,80 +1,106 @@
#!/usr/bin/env python3 #!/usr/bin/python3
#_______________________________________________________________________________________________________________________________
#
# Formato de salida:
# disk=Número de disco\tpar=Número de particion\tcod=Código de partición\tsfi=Sistema de ficheros\tsoi=Sistema instalado\ttam=Tamaño de la partición\n
#_______________________________________________________________________________________________________________________________
import os import os
import glob
import subprocess import subprocess
def run_command(command): from InventoryLib import ogGetSerialNumber, ogGetOsVersion
result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) from DiskLib import ogDiskToDev, ogGetPartitionsNumber, ogGetPartitionTableType, ogGetDiskSize, ogGetPartitionId, ogGetPartitionSize
return result.stdout.decode().strip() from FileSystemLib import ogMount, ogGetMountPoint, ogGetFsType
def main(): # No registrar los errores.
# No registrar los errores. #os.environ['DEBUG'] = 'no'
os.environ["DEBUG"] = "no"
ser = run_command("ogGetSerialNumber") ser = ogGetSerialNumber()
cfg = "" cfg = ''
disks = int(run_command("ogDiskToDev | wc -w")) disks = len (ogDiskToDev())
for dsk in range(1, disks + 1): for dsk in range (1, disks+1):
particiones = run_command(f"ogGetPartitionsNumber {dsk}") particiones = ogGetPartitionsNumber (dsk)
particiones = int(particiones) if particiones else 0 particiones = int (particiones) if particiones else 0
ptt = run_command(f"ogGetPartitionTableType {dsk}") # Tipo de tabla de particiones: 1=MSDOS, 2=GPT
ptt = ogGetPartitionTableType (dsk)
ptt_map = { ptt_map = {
"MSDOS": 1, 'MSDOS': 1,
"GPT": 2, 'GPT': 2,
"LVM": 3, 'LVM': 3,
"ZPOOL": 4 'ZPOOL': 4,
} }
ptt = ptt_map.get(ptt, 0) ptt = ptt_map.get (ptt, 0)
# Información de disco (partición 0)
cfg += f"{dsk}:0:{ptt}:::{run_command(f'ogGetDiskSize {dsk}')}:0;" s = ogGetDiskSize (dsk)
cfg += f'{dsk}:0:{ptt}:::{s}:0;'
for par in range(1, particiones + 1): for par in range (1, particiones+1):
cod = run_command(f"ogGetPartitionId {dsk} {par} 2>/dev/null") # Código del identificador de tipo de partición
fsi = run_command(f"getFsType {dsk} {par} 2>/dev/null") or "EMPTY" cod = ogGetPartitionId (dsk, par)
tam = run_command(f"ogGetPartitionSize {dsk} {par} 2>/dev/null") or "0" # Tipo del sistema de ficheros
soi = "" fsi = ogGetFsType (dsk, par)
uso = 0 if not fsi: fsi = 'EMPTY'
# Tamaño de la particón
if fsi not in ["", "EMPTY", "LINUX-SWAP", "LINUX-LVM", "ZVOL"]: tam = ogGetPartitionSize (dsk, par)
if run_command(f"ogMount {dsk} {par} 2>/dev/null"): if not tam: tam = '0'
soi = run_command(f"getOsVersion {dsk} {par} 2>/dev/null").split(":")[1] # Sistema operativo instalado
if not soi: soi = ''
soi = run_command(f"getOsVersion {dsk} {par} 2>/dev/null").split(":")[1] uso = '0'
if not soi and fsi not in ["EMPTY", "CACHE"]: if fsi not in ['', 'EMPTY', 'LINUX-SWAP', 'LINUX-LVM', 'ZVOL']:
soi = "DATA" if ogMount (dsk, par):
uso = int(run_command(f"df $(ogGetMountPoint {dsk} {par}) | awk '{{getline; printf \"%d\",$5}}'") or 0) soi = ogGetOsVersion (dsk, par)
else: # Hacer un 2º intento para algunos casos especiales.
soi = "" if not soi:
uso = 0 soi = ogGetOsVersion (dsk, par)
if not soi: soi = ''
cfg += f"{dsk}:{par}:{cod}:{fsi}:{soi}:{tam}:{uso};" if soi: soi = soi.split (':')[1]
# Sistema de archivos para datos (sistema operativo "DATA")
if not cfg: if not soi and fsi not in ['EMPTY', 'CACHE']:
cfg = "1:0:0:::0;" soi = 'DATA'
# Obtener porcentaje de uso.
cfgfile = "/tmp/getconfig" mntpt = ogGetMountPoint (dsk, par)
with open(cfgfile, "w") as f: uso = subprocess.run (['df', mntpt], capture_output=True, text=True).stdout.splitlines()[-1].split()[4].replace ('%', '')
f.write(f"{ser + ';' if ser else ''}{cfg}") if not uso: uso = '0'
run_command("generateMenuDefault &>/dev/null")
with open(cfgfile, "r") as f:
data = f.read()
lines = data.split(";")
for line in lines:
if line:
parts = line.split(":")
if len(parts) == 1:
print(f"ser={parts[0]}")
else: else:
print(f"disk={parts[0]}\tpar={parts[1]}\tcpt={parts[2]}\tfsi={parts[3]}\tsoi={parts[4]}\ttam={parts[5]}\tuso={parts[6]}") soi = ''
uso = '0'
run_command("rm -f /mnt/*/ogboot.* /mnt/*/*/ogboot.*") cfg += f'{dsk}:{par}:{cod}:{fsi}:{soi}:{tam}:{uso};'
# Volver a registrar los errores. # Crear configuración por defecto para cliente sin disco.
os.environ.pop("DEBUG", None) if not cfg:
cfg = '1:0:0:::0;'
# Guardar salida en fichero temporal.
cfgfile = '/tmp/getconfig'
with open (cfgfile, 'w') as f:
if ser: f.write (f'{ser};\n')
f.write (cfg + '\n')
# Crear el menú por defecto a partir del fichero generado (no dar ninguna salida).
#subprocess.run ([f'{ogGlobals.OGSCRIPTS}/generateMenuDefault'])
# Componer salida formateada.
awk_script = r'''{ n=split($0,sep,";");
for (i=1; i<n; i++){
c=split (sep[i],dua,":");
if (i==1 && c==1)
printf ("ser=%s\n", dua[1]);
else
printf ("disk=%s\tpar=%s\tcpt=%s\tfsi=%s\tsoi=%s\ttam=%s\tuso=%s\n",
dua[1],dua[2],dua[3],dua[4],dua[5],dua[6],dua[7]);
}
}
'''
print (f'nati awk_script ({awk_script})')
subprocess.run (['awk', awk_script, cfgfile])
# Borramos marcas de arranque de Windows
for f in glob.glob ('/mnt/*/ogboot.*') + glob.glob ('/mnt/*/*/ogboot.*'):
os.unlink (f)
# Volver a registrar los errores.
#os.environ.pop('DEBUG', None)
if __name__ == "__main__":
main()