voixicron.py 6.0 KB

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