voixicron.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. __version__ = "0.3"
  17. # Configuration parameters used to send notifications and change the logging
  18. # behaviour
  19. CONFIG = {
  20. "admin_email": "root",
  21. "smtp_server": "localhost",
  22. "smtp_port": 25,
  23. "smtp_user": "",
  24. "smtp_password": "",
  25. "log_level": logging.ERROR,
  26. }
  27. AVAILABLE_UPDATES = []
  28. DEVNULL = open("/dev/null", "w")
  29. LOGGER = logging.getLogger("voixicron")
  30. LOGGER.setLevel(CONFIG["log_level"])
  31. CONSOLE_HANDLER = logging.StreamHandler()
  32. LOGGER.addHandler(CONSOLE_HANDLER)
  33. try:
  34. subprocess.call(["xbps-install", "-S"], stdout=DEVNULL, stderr=DEVNULL)
  35. except subprocess.CalledProcessError:
  36. LOGGER.warn("Repository information could not be updated, voixicron will "
  37. "report outdated data!")
  38. try:
  39. XBPS_INSTALL_RESULT = subprocess.check_output(["xbps-install", "-Sun"],
  40. stderr=DEVNULL)
  41. except subprocess.CalledProcessError as error:
  42. LOGGER.error("Could not get list of updated packages, xbps-install error:"
  43. " %s", error.output)
  44. sys.exit(1)
  45. else:
  46. XBPS_INSTALL_RESULT = XBPS_INSTALL_RESULT.decode("utf-8").split("\n")
  47. for line in XBPS_INSTALL_RESULT:
  48. if "update" in line:
  49. try:
  50. package = line.split(" ")[0]
  51. package_regex = "^([A-Za-z0-9-._+]*)-([0-9].*_[0-9]*)$"
  52. match_object = re.match(package_regex, package)
  53. if match_object:
  54. package_name = match_object.groups()[0]
  55. new_package_version = match_object.groups()[1]
  56. else:
  57. LOGGER.error("Not match for package %s", package)
  58. continue
  59. except IndexError:
  60. continue
  61. else:
  62. try:
  63. xbps_query_result = subprocess.check_output(
  64. ["xbps-query", "--show", package_name], stderr=DEVNULL)
  65. except subprocess.CalledProcessError as error:
  66. LOGGER.debug("Querying the installed version of package %s"
  67. " failed with error message: %s",
  68. package_name, error.output)
  69. else:
  70. xbps_query_result = xbps_query_result.decode(
  71. "utf-8").split("\n")
  72. for line in xbps_query_result:
  73. if "pkgver" in line:
  74. installed_package = line.split(
  75. ":")[1].strip()
  76. match = re.match(package_regex,
  77. installed_package)
  78. if match:
  79. installed_package_version = match.groups()[1]
  80. package_update = {
  81. "name": package_name,
  82. "new_version": new_package_version,
  83. "old_version": installed_package_version,
  84. }
  85. else:
  86. LOGGER.error("Unable to detect installed "
  87. "version of package %s",
  88. package_name)
  89. package_update = {
  90. "name": package_name,
  91. "new_version": new_package_version,
  92. "old_version": "unknown",
  93. }
  94. AVAILABLE_UPDATES.append(package_update)
  95. break
  96. if AVAILABLE_UPDATES:
  97. HOSTNAME = socket.getfqdn()
  98. MSG = MIMEMultipart()
  99. MAIL_TEXT = "The following package updates are available on host %s:\n\n"\
  100. % HOSTNAME
  101. MSG["Subject"] = "%s updates available on host %s"\
  102. % (len(AVAILABLE_UPDATES), HOSTNAME)
  103. MSG["From"] = "voixicron@%s" % HOSTNAME
  104. MSG["To"] = CONFIG["admin_email"]
  105. for update in AVAILABLE_UPDATES:
  106. MAIL_TEXT += "%s (%s -> %s)\n"\
  107. % (update["name"],
  108. update["old_version"],
  109. update["new_version"])
  110. MAIL_TEXT += "\n\nYou can install the updates by issuing the command:" \
  111. "\n\n\txbps-install -Su\n\nas root on %s\n\n--\nvoixicron"\
  112. % HOSTNAME
  113. MSG_TEXT = MIMEText(MAIL_TEXT.encode("utf-8"), _charset="utf-8")
  114. MSG.attach(MSG_TEXT)
  115. SERVER_CONNECTION = smtplib.SMTP(CONFIG["smtp_server"],
  116. CONFIG["smtp_port"])
  117. try:
  118. SERVER_CONNECTION.connect()
  119. except (smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected,
  120. socket.error):
  121. LOGGER.error("Failed to establish a connection to the SMTP server")
  122. else:
  123. try:
  124. SERVER_CONNECTION.starttls()
  125. except smtplib.SMTPException:
  126. pass
  127. if CONFIG["smtp_user"]:
  128. try:
  129. SERVER_CONNECTION.login(CONFIG["smtp_user"],
  130. CONFIG["smtp_password"])
  131. except smtplib.SMTPAuthenticationError:
  132. LOGGER.error("Authentication on the mail server with user %s "
  133. "failed.", CONFIG["smtp_user"])
  134. except smtplib.SMTPException:
  135. LOGGER.error("Error during authentication on the mail server.")
  136. try:
  137. SERVER_CONNECTION.sendmail("voixicron@%s" % HOSTNAME,
  138. CONFIG["admin_email"],
  139. MSG.as_string())
  140. except smtplib.SMTPRecipientsRefused:
  141. LOGGER.error("The mail server refused the recipient.")
  142. except smtplib.SMTPSenderRefused:
  143. LOGGER.error("The mail server refused the sender.")
  144. else:
  145. SERVER_CONNECTION.quit()
  146. DEVNULL.close()