Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- import datetime
- import smtplib
- from email.mime.text import MIMEText
- from email.mime.multipart import MIMEMultipart
- import locale
- #------------------------ [Var & Const def] -----------------------------------------------
- # Set the locale to French for date formatting
- locale.setlocale(locale.LC_TIME, "fr_FR.UTF-8")
- # List of products to monitor
- PRODUCTS = [
- "ubuntu-server", "windows-server"
- ]
- # Email sending settings
- SMTP_SERVER = "<your-smtp-server>" # Replace with your SMTP server
- SMTP_PORT = 25 # Using port 25 without authentication
- EMAIL_FROM = "<your-sender>" # Replace with your email
- EMAIL_TO = "<your-recipient>" # Replace with recipient's email
- #------------------------------------- [Functions] ---------------------------------------
- def get_end_of_life_info(product):
- """Fetches end-of-life information and the real product name."""
- print(f"Fetching data for product: {product}")
- url = f"https://endoflife.date/api/{product}.json"
- try:
- response = requests.get(url)
- if response.status_code == 200:
- data = response.json()
- if data:
- # Retrieve the real product name from the API
- product_name = data[0].get("name", product.capitalize())
- return product_name, data
- else:
- print(f"HTTP error {response.status_code} for {product}")
- return product.capitalize(), None
- except Exception as e:
- print(f"Error fetching data for {product}: {e}")
- return product.capitalize(), None
- def filter_supported_versions(data):
- """Filters versions whose end-of-life is in one year or less."""
- today = datetime.date.today()
- one_year_later = today + datetime.timedelta(days=365)
- filtered_versions = []
- for entry in data:
- eol_date_str = entry.get("eol")
- # Check if the date is valid and usable
- if isinstance(eol_date_str, str) and eol_date_str.lower() != "false":
- try:
- eol_date = datetime.datetime.strptime(eol_date_str, "%Y-%m-%d").date()
- if today <= eol_date <= one_year_later:
- formatted_date = eol_date.strftime("%d %B %Y") # E.g.: "26 March 2025"
- filtered_versions.append((entry.get("cycle", "Unknown"), eol_date, formatted_date, entry.get("latest")))
- except ValueError:
- print(f"Error parsing end-of-life date for {entry}: {eol_date_str}")
- return filtered_versions
- def get_row_class(eol_date):
- """Returns the CSS class to apply to the row depending on support end date."""
- today = datetime.date.today()
- two_months_later = today + datetime.timedelta(days=60)
- six_months_later = today + datetime.timedelta(days=180)
- if eol_date <= two_months_later:
- return "red"
- elif eol_date <= six_months_later:
- return "orange"
- else:
- return "green"
- def generate_html_table():
- """Generates an HTML table of soon-to-be unsupported versions, one table per product."""
- all_tables_html = ""
- for product in PRODUCTS:
- product_name, data = get_end_of_life_info(product)
- if data:
- filtered_versions = filter_supported_versions(data)
- if filtered_versions:
- # Sort versions by end-of-life date (furthest first)
- filtered_versions.sort(key=lambda x: x[1], reverse=True)
- # Use real name in the title
- table_html = f"""
- <h2>{product_name}</h2>
- <table>
- <tr>
- <th>Version</th>
- <th>Latest Version</th>
- <th>End of Support</th>
- </tr>
- """
- for cycle, eol_date, formatted_date, latest in filtered_versions:
- row_class = get_row_class(eol_date)
- table_html += f"""
- <tr class="{row_class}">
- <td>{cycle}</td>
- <td>{latest}</td>
- <td>{formatted_date}</td>
- </tr>
- """
- table_html += "</table>"
- all_tables_html += table_html
- if not all_tables_html:
- return None
- # Add CSS for table styling
- return f"""
- <html>
- <head>
- <style>
- body {{ font-family: Arial, sans-serif; }}
- h2 {{ font-size: 18px; margin-top: 20px; }}
- table {{ width: auto; border-collapse: collapse; margin-bottom: 20px; }}
- th, td {{ padding: 4px 8px; text-align: left; border: 1px solid #ddd; }}
- .red {{ background-color: #FF0000; }} /* Red */
- .orange {{ background-color: #FFA500; }} /* Orange */
- .green {{ background-color: #90EE90; }} /* Green */
- </style>
- </head>
- <body>
- {all_tables_html}
- </body>
- </html>
- """
- def send_email(table_html):
- """Sends an HTML email with the table of soon-to-be unsupported versions."""
- msg = MIMEMultipart()
- msg['From'] = EMAIL_FROM
- msg['To'] = EMAIL_TO
- msg['Subject'] = "Alert: End of Support for Software Versions"
- body = f"""
- <html>
- <body>
- <p>Hello,</p>
- <p>Here is the list of versions whose end of support is within one year:</p>
- {table_html}
- <p>Best regards,<br>Your Monitoring System</p>
- </body>
- </html>
- """
- msg.attach(MIMEText(body, 'html'))
- try:
- print("Attempting to connect to SMTP server...")
- server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
- server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
- server.quit()
- print("Email sent successfully.")
- except smtplib.SMTPException as e:
- print(f"SMTP error when sending email: {e}")
- except Exception as e:
- print(f"General error when sending email: {e}")
- # --------------------------- [Main] ------------------------------------
- if __name__ == "__main__":
- table_html = generate_html_table()
- if table_html:
- print("Table generated successfully")
- send_email(table_html)
- else:
- print("No product to display.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement