voixicron.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. package_name = match_object.groups()[0]
  50. new_package_version = match_object.groups()[1]
  51. except IndexError:
  52. continue
  53. else:
  54. try:
  55. xbps_query_result = subprocess.check_output(
  56. ["xbps-query", "--show", package_name], stderr=DEVNULL)
  57. except subprocess.CalledProcessError as error:
  58. LOGGER.debug("Querying the installed version of package %s"
  59. " failed with error message: %s"
  60. %(package_name, error.output))
  61. else:
  62. xbps_query_result = xbps_query_result.decode(
  63. "utf-8").split("\n")
  64. for line in xbps_query_result:
  65. if "pkgver" in line:
  66. installed_package = line.split(
  67. ":")[1].strip()
  68. match = re.match(package_regex,
  69. installed_package)
  70. installed_package_version = match.groups()[1]
  71. package_update = {
  72. "name": package_name,
  73. "new_version": new_package_version,
  74. "old_version": installed_package_version,
  75. }
  76. AVAILABLE_UPDATES.append(package_update)
  77. break
  78. if AVAILABLE_UPDATES:
  79. HOSTNAME = socket.getfqdn()
  80. MSG = MIMEMultipart()
  81. MAIL_TEXT = "The following package updates are available on host %s:\n\n"\
  82. % HOSTNAME
  83. MSG["Subject"] = "%s updates available on host %s"\
  84. % (len(AVAILABLE_UPDATES), HOSTNAME)
  85. MSG["From"] = "voixicron@%s" % HOSTNAME
  86. MSG["To"] = ADMIN_EMAIL
  87. for update in AVAILABLE_UPDATES:
  88. MAIL_TEXT += "%s (%s -> %s)\n"\
  89. % (update["name"],
  90. update["old_version"],
  91. update["new_version"])
  92. MSG_TEXT = MIMEText(MAIL_TEXT.encode("utf-8"), _charset="utf-8")
  93. MSG.attach(MSG_TEXT)
  94. SERVER_CONNECTION = smtplib.SMTP(MAIL_SERVER, MAIL_SERVER_PORT)
  95. try:
  96. SERVER_CONNECTION.connect()
  97. except (smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected,
  98. socket.error):
  99. LOGGER.error("Failed to establish a connection to the SMTP server")
  100. else:
  101. try:
  102. SERVER_CONNECTION.starttls()
  103. except smtplib.SMTPException:
  104. pass
  105. if MAIL_SERVER_USER:
  106. try:
  107. SERVER_CONNECTION.login(MAIL_SERVER_USER, MAIL_SERVER_PASSWORD)
  108. except smtplib.SMTPAuthenticationError:
  109. LOGGER.error("Authentication on the mail server with user %s "
  110. "failed." % MAIL_SERVER_USER)
  111. except smtplib.SMTPException:
  112. LOGGER.error("Error during authentication on the mail server.")
  113. try:
  114. SERVER_CONNECTION.sendmail("voixicron@%s" % HOSTNAME, ADMIN_EMAIL,
  115. MSG.as_string())
  116. except smtplib.SMTPRecipientsRefused:
  117. LOGGER.error("The mail server refused the recipient.")
  118. except smtplib.SMTPSenderRefused:
  119. LOGGER.error("The mail server refused the sender.")
  120. else:
  121. SERVER_CONNECTION.quit()
  122. DEVNULL.close()