voixicron.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. #! /usr/bin/env python3
  2. """
  3. This script checks for available updates on Void Linux using xbps and notifies
  4. the configured administrator account about them. It currently requires
  5. python 3.x and no additional packages and is supposed to be run with cron or
  6. another scheduled execution mechanism.
  7. """
  8. import subprocess
  9. import smtplib
  10. import socket
  11. import re
  12. import logging
  13. import sys
  14. from email.mime.multipart import MIMEMultipart
  15. from email.mime.text import MIMEText
  16. # Email server to be used to send the notification
  17. ADMIN_EMAIL = "root"
  18. # Mail server to be used to send the notification
  19. MAIL_SERVER = "localhost"
  20. # Port to use on the mail server
  21. MAIL_SERVER_PORT = 25
  22. # User name to log in to the mail server
  23. MAIL_SERVER_USER = ""
  24. # Password to log in to the mail server
  25. MAIL_SERVER_PASSWORD = ""
  26. # Log level for the stderr/stdout output
  27. LOG_LEVEL = logging.ERROR
  28. AVAILABLE_UPDATES = []
  29. DEVNULL = open("/dev/null", "w")
  30. LOGGER = logging.getLogger("voixicron")
  31. LOGGER.setLevel(LOG_LEVEL)
  32. CONSOLE_HANDLER = logging.StreamHandler()
  33. LOGGER.addHandler(CONSOLE_HANDLER)
  34. try:
  35. XBPS_INSTALL_RESULT = subprocess.check_output(["xbps-install", "-Sun"],
  36. stderr=DEVNULL)
  37. except subprocess.CalledProcessError as error:
  38. LOGGER.error("Could not get list of updated packages, xbps-install error:"
  39. " %s", error.output)
  40. sys.exit(1)
  41. else:
  42. XBPS_INSTALL_RESULT = XBPS_INSTALL_RESULT.decode("utf-8").split("\n")
  43. for line in XBPS_INSTALL_RESULT:
  44. if "update" in line:
  45. try:
  46. package = line.split(" ")[0]
  47. package_regex = "^([A-Za-z0-9-._]*)-([0-9].*_[0-9]*)$"
  48. match_object = re.match(package_regex, package)
  49. if match_object:
  50. package_name = match_object.groups()[0]
  51. new_package_version = match_object.groups()[1]
  52. else:
  53. LOGGER.error("Not match for package %s", package)
  54. continue
  55. except IndexError:
  56. continue
  57. else:
  58. try:
  59. xbps_query_result = subprocess.check_output(
  60. ["xbps-query", "--show", package_name], stderr=DEVNULL)
  61. except subprocess.CalledProcessError as error:
  62. LOGGER.debug("Querying the installed version of package %s"
  63. " failed with error message: %s",
  64. package_name, error.output)
  65. else:
  66. xbps_query_result = xbps_query_result.decode(
  67. "utf-8").split("\n")
  68. for line in xbps_query_result:
  69. if "pkgver" in line:
  70. installed_package = line.split(
  71. ":")[1].strip()
  72. match = re.match(package_regex,
  73. installed_package)
  74. if match:
  75. installed_package_version = match.groups()[1]
  76. package_update = {
  77. "name": package_name,
  78. "new_version": new_package_version,
  79. "old_version": installed_package_version,
  80. }
  81. else:
  82. LOGGER.error("Unable to detect installed "
  83. "version of package %s",
  84. package_name)
  85. package_update = {
  86. "name": package_name,
  87. "new_version": new_package_version,
  88. "old_version": "unknown",
  89. }
  90. AVAILABLE_UPDATES.append(package_update)
  91. break
  92. if AVAILABLE_UPDATES:
  93. HOSTNAME = socket.getfqdn()
  94. MSG = MIMEMultipart()
  95. MAIL_TEXT = "The following package updates are available on host %s:\n\n"\
  96. % HOSTNAME
  97. MSG["Subject"] = "%s updates available on host %s"\
  98. % (len(AVAILABLE_UPDATES), HOSTNAME)
  99. MSG["From"] = "voixicron@%s" % HOSTNAME
  100. MSG["To"] = ADMIN_EMAIL
  101. for update in AVAILABLE_UPDATES:
  102. MAIL_TEXT += "%s (%s -> %s)\n"\
  103. % (update["name"],
  104. update["old_version"],
  105. update["new_version"])
  106. MAIL_TEXT += "\n\nYou can install the updates by issuing the command:" \
  107. "\n\n\txbps-install -Su\n\nas root on %s\n\n--\nvoixicron"\
  108. % HOSTNAME
  109. MSG_TEXT = MIMEText(MAIL_TEXT.encode("utf-8"), _charset="utf-8")
  110. MSG.attach(MSG_TEXT)
  111. SERVER_CONNECTION = smtplib.SMTP(MAIL_SERVER, MAIL_SERVER_PORT)
  112. try:
  113. SERVER_CONNECTION.connect()
  114. except (smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected,
  115. socket.error):
  116. LOGGER.error("Failed to establish a connection to the SMTP server")
  117. else:
  118. try:
  119. SERVER_CONNECTION.starttls()
  120. except smtplib.SMTPException:
  121. pass
  122. if MAIL_SERVER_USER:
  123. try:
  124. SERVER_CONNECTION.login(MAIL_SERVER_USER, MAIL_SERVER_PASSWORD)
  125. except smtplib.SMTPAuthenticationError:
  126. LOGGER.error("Authentication on the mail server with user %s "
  127. "failed.", MAIL_SERVER_USER)
  128. except smtplib.SMTPException:
  129. LOGGER.error("Error during authentication on the mail server.")
  130. try:
  131. SERVER_CONNECTION.sendmail("voixicron@%s" % HOSTNAME, ADMIN_EMAIL,
  132. MSG.as_string())
  133. except smtplib.SMTPRecipientsRefused:
  134. LOGGER.error("The mail server refused the recipient.")
  135. except smtplib.SMTPSenderRefused:
  136. LOGGER.error("The mail server refused the sender.")
  137. else:
  138. SERVER_CONNECTION.quit()
  139. DEVNULL.close()