updateSquid.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import json
  2. import os
  3. import platform
  4. import shutil
  5. import subprocess
  6. import tempfile
  7. from dotenv import load_dotenv
  8. from loguru import logger
  9. load_dotenv()
  10. def update_squid():
  11. squid_bin = shutil.which("squid")
  12. try:
  13. if squid_bin:
  14. pre_check = subprocess.run( # noqa: S603
  15. [squid_bin, "-v"], capture_output=True, text=True
  16. )
  17. squid_instalado = pre_check.returncode == 0
  18. else:
  19. squid_instalado = False
  20. except FileNotFoundError:
  21. squid_instalado = False
  22. if squid_instalado:
  23. logger.info(f"Squid ya está instalado: {pre_check.stdout.strip()}")
  24. else:
  25. logger.info(
  26. "El binario de Squid no se encontró en el sistema (aún no instalado)"
  27. if not squid_bin
  28. else "Squid no está instalado o no se detectó instalación previa"
  29. )
  30. try:
  31. os_info = platform.freedesktop_os_release()
  32. os_id = os_info.get("ID", "").lower()
  33. codename = os_info.get(
  34. "VERSION_CODENAME", os_info.get("UBUNTU_CODENAME", "")
  35. ).lower()
  36. if os_id not in ["ubuntu", "debian"] or not codename:
  37. print("Sistema operativo no compatible", "error")
  38. return False
  39. proxy_url = os.getenv("HTTP_PROXY", "")
  40. env = os.environ.copy()
  41. if proxy_url:
  42. env["http_proxy"] = proxy_url
  43. env["https_proxy"] = proxy_url
  44. wget_bin = shutil.which("wget")
  45. if not wget_bin:
  46. logger.error("wget no encontrado en el sistema")
  47. return False
  48. version_info = subprocess.run( # noqa: S603
  49. [
  50. wget_bin,
  51. "-qO-",
  52. "https://api.github.com/repos/cuza/squid/releases/latest",
  53. ],
  54. capture_output=True,
  55. text=True,
  56. env=env,
  57. )
  58. if version_info.returncode != 0:
  59. logger.error("Error obteniendo información de versión")
  60. return False
  61. try:
  62. latest_version = json.loads(version_info.stdout)["tag_name"]
  63. except (json.JSONDecodeError, KeyError):
  64. logger.error("Error procesando versión")
  65. return False
  66. package_name = f"squid_{latest_version}-{os_id}-{codename}_amd64.deb"
  67. download_url = f"https://github.com/cuza/squid/releases/download/{latest_version}/{package_name}"
  68. check_package = subprocess.run( # noqa: S603
  69. [wget_bin, "--spider", download_url],
  70. capture_output=True,
  71. text=True,
  72. env=env,
  73. )
  74. if check_package.returncode != 0:
  75. logger.error(
  76. f"Paquete no disponible para {os_id.capitalize()} {codename.capitalize()}"
  77. )
  78. return False
  79. with tempfile.NamedTemporaryFile(
  80. delete=False, suffix=f"_{package_name}"
  81. ) as tmp_pkg:
  82. package_path = tmp_pkg.name
  83. download = subprocess.run( # noqa: S603
  84. [wget_bin, download_url, "-O", package_path],
  85. capture_output=True,
  86. text=True,
  87. env=env,
  88. )
  89. if download.returncode != 0:
  90. logger.error("Error descargando el paquete")
  91. return False
  92. apt_env = env.copy()
  93. if proxy_url:
  94. apt_conf = "/etc/apt/apt.conf.d/95proxies"
  95. with open(apt_conf, "w") as f:
  96. f.write(f'Acquire::http::Proxy "{proxy_url}";\n')
  97. f.write(f'Acquire::https::Proxy "{proxy_url}";\n')
  98. apt_bin = shutil.which("apt")
  99. dpkg_bin = shutil.which("dpkg")
  100. cp_bin = shutil.which("cp")
  101. chmod_bin = shutil.which("chmod")
  102. systemctl_bin = shutil.which("systemctl")
  103. if apt_bin:
  104. subprocess.run([apt_bin, "update"], env=apt_env) # noqa: S603
  105. if dpkg_bin:
  106. install = subprocess.run( # noqa: S603
  107. [dpkg_bin, "-i", "--force-overwrite", package_path]
  108. )
  109. if install.returncode != 0:
  110. logger.error("Error instalando el paquete")
  111. if apt_bin:
  112. subprocess.run([apt_bin, "install", "-f", "-y"], env=apt_env) # noqa: S603
  113. if cp_bin:
  114. subprocess.run([cp_bin, f"{os.getcwd()}/./utils/squid", "/etc/init.d/"]) # noqa: S603
  115. if chmod_bin:
  116. subprocess.run([chmod_bin, "+x", "/etc/init.d/squid"]) # noqa: S603
  117. if systemctl_bin:
  118. subprocess.run([systemctl_bin, "daemon-reload"]) # noqa: S603
  119. os.unlink(package_path)
  120. squid_bin_final = shutil.which("squid")
  121. if squid_bin_final:
  122. squid_check = subprocess.run( # noqa: S603
  123. [squid_bin_final, "-v"], capture_output=True, text=True
  124. )
  125. if squid_check.returncode != 0:
  126. logger.error("Error en instalación final")
  127. return False
  128. logger.info(f"Actualización a {latest_version} completada exitosamente")
  129. return True
  130. except Exception:
  131. logger.exception("Error crítico durante la actualización de Squid")
  132. return False