refs #521 - Add sendfileUFTP.py

pull/1/head
Gerardo GIl Elizeire 2024-07-26 13:10:07 +02:00
parent 63f966d29d
commit b3399b9d5d
1 changed files with 132 additions and 0 deletions

132
bin/sendFileUFTP.py 100644
View File

@ -0,0 +1,132 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Este script envía mediante UFTP la imagen recibida como primer parámetro, al puerto e IP (Multicast o Unicast) especificados en el segundo parámetro,
a la velocidad de transferencia tambíén especificada en el segundo parámetro (la sintaxis de este parámetro es "puerto:ip:bitrate").
Previamente, los clientes deben haberse puesto a escuchar en la IP Multicast correspondiente (tanto para envíos Multicast como para envíos Unicast).
- Parámetros:
--------------
sys.argv[1] - Nombre completo de la imagen a enviar (con o sin ruta)
- Ejemplo1: image1.img
- Ejemplo2: /opt/opengnsys/images/image1.img
sys.argv[2] - Parámetros Multicast/Unicast (en formato "puerto:ip:bitrate")
- Ejemplo1: 9000:239.194.17.2:100M
- Ejemplo2: 9000:192.168.56.101:1G
- Sintaxis:
./sendFileUFTP.py image_name|/image_path/image_name port:ip:bitrate
- Ejemplos:
./sendFileUFTP.py image1.img 9000:239.194.17.2:100M
./sendFileUFTP.py /opt/opengnsys/images/image1.img 9000:192.168.56.101:1G
"""
# --------------------------------------------------------------------------------------------
import os
import sys
import subprocess
# --------------------------------------------------------------------------------------------
script_name = os.path.basename(__file__)
repo_path = '/opt/opengnsys/images/'
#REPO_IFACE = subprocess.getoutput('/opt/opengnsys/bin/getRepoIface') # Para poder ejecutar esto tengo que ejecutar el script con sudo, pero no sé si es necesario (de momento no lo estoy usando)
#print(REPO_IFACE)
log_file = '/opt/opengnsys/images/uftp.log'
# --------------------------------------------------------------------------------------------
def show_help():
""" Imprime la ayuda (cuando se ejecuta el script con el parámetro "help").
"""
help_text = f"""
Sintaxis: {script_name} image_name|/image_path/image_name port:ip:bitrate
Ejemplo1: {script_name} image1.img 9000:239.194.17.2:100M
Ejemplo2: {script_name} /opt/opengnsys/images/image1.img 9000:192.168.56.101:1G
"""
print(help_text)
# Si se ejecuta el script con el parámetro "help", se muestra la ayuda, y se sale del script:
if len(sys.argv) == 2 and sys.argv[1] == "help":
show_help()
sys.exit(0)
# Si se ejecuta la función con más o menos de 2 parámetros, se muestra un mensaje de error, y se sale del script:
if len(sys.argv) != 3:
print(f"{script_name} Error: Formato incorrecto: Se debe especificar 2 parámetros (image_name|/image_path/image_name port:ip:bitrate)")
sys.exit(1)
def build_file_path():
""" Construye la ruta completa al archivo a enviar
(agregando "/opt/opengnsys/images/" si no se ha especificado en el parámetro).
"""
param_path = sys.argv[1]
if not param_path.startswith(repo_path):
file_path = os.path.join(repo_path, param_path)
else:
file_path = param_path
return file_path
# --------------------------------------------------------------------------------------------
def main():
"""
"""
# Obtenemos la ruta completa al archivo a enviar:
file_path = build_file_path()
# Si el fichero no es accesible, devolvermos un error, y salimos del script:
if not os.path.isfile(file_path):
print(f"{script_name} Error: Fichero \"{file_path}\" no accesible")
sys.exit(2)
# Si en el segundo parámetro no hay 3 elementos (separados por ":"), devolvermos un error, y salimos del script:
params = sys.argv[2].split(':')
if len(params) != 3:
print(f"{script_name} Error: Datos Multicast incorrectos: \"{sys.argv[2]}\" (se debe especificar \"puerto:ip:bitrate\")")
sys.exit(3)
# Almacenamos los elementos del segundo parámetro en variables:
port, ip, bitrate = params
# Calculamos el valor de la variable "bitrate", en base a la letra especificada (que luego eliminamos de la variable):
bitrate = bitrate.lower()
if "m" in bitrate:
bitrate = int(bitrate.strip("m")) * 1024
elif "g" in bitrate:
bitrate = int(bitrate.strip("g")) * 1024 * 1024
else:
bitrate = int(bitrate.strip("k"))
# Creamos una lista con el comando a enviar (esto es requerido por la función "subprocess.run"), e impimimos el comando con espacios:
splitted_cmd = f"uftp -M {ip} -p {port} -L {log_file} -Y aes256-cbc -h sha256 -e rsa -c -K 1024 -R {bitrate} {file_path}".split()
print(f"Sending command: {' '.join(splitted_cmd)}")
# Ejecutamos el comando en el sistema, e imprimimos el resultado:
try:
result = subprocess.run(splitted_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"ReturnCode: {result.returncode}")
except subprocess.CalledProcessError as error:
print(f"ReturnCode: {error.returncode}")
print(f"Error Output: {error.stderr.decode()}")
except Exception as error:
print(f"Se ha producido un error inesperado: {error}")
# --------------------------------------------------------------------------------------------
if __name__ == "__main__":
main()
# --------------------------------------------------------------------------------------------