import requests
import smtplib
import ssl
import tempfile
import time
import urllib.request
import json
import logging
from datetime import datetime, timedelta
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Logging configuration
log_file = "/var/log/script_log.log"
logging.basicConfig(filename=log_file, level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
def send_to_telegram(bot_token, chat_id, caption, *image_paths):
url = f"https://api.telegram.org/bot{bot_token}/sendMediaGroup"
media_group = []
for i, image_path in enumerate(image_paths):
media_group.append({
'type': 'photo',
'media': 'attach://image' + str(i),
'caption': caption if i == 0 else "",
'parse_mode': 'HTML',
})
data = {
'chat_id': chat_id,
'media': json.dumps(media_group),
}
files = {
f'image{i}': (f'image{i}.jpg', open(image_path, 'rb')) for i, image_path in enumerate(image_paths)
}
response = requests.post(url, data=data, files=files)
if response.status_code != 200:
raise ValueError(f"Request to Telegram API returned an error: {response.status_code}, {response.text}")
def create_email(sender_email, recipient_emails, subject, boot_time_str, image_path1, image_path2):
msg = MIMEMultipart("related")
msg["From"] = sender_email
msg["To"] = ",".join(recipient_emails)
msg["Subject"] = subject
msg_alternative = MIMEMultipart("alternative")
msg.attach(msg_alternative)
msg_text = MIMEText("This is the alternative plain text message.")
msg_alternative.attach(msg_text)
html_text = f'

Letzter Start: {boot_time_str} Uhr
'
msg_html = MIMEText(html_text, "html")
msg_alternative.attach(msg_html)
with open(image_path1, "rb") as file:
msg_image1 = MIMEImage(file.read())
msg_image1.add_header("Content-ID", "")
msg.attach(msg_image1)
with open(image_path2, "rb") as file:
msg_image2 = MIMEImage(file.read())
msg_image2.add_header("Content-ID", "")
msg.attach(msg_image2)
return msg
def send_email(sender_email, recipient_emails, msg):
try:
context = ssl.create_default_context()
with smtplib.SMTP("smtp.web.de", 587) as server:
server.ehlo()
server.starttls(context=context)
server.ehlo()
server.login(sender_email, "PV-Tannenstr1")
server.sendmail(sender_email, recipient_emails, msg.as_string())
logging.info("Email sent successfully.")
except Exception as e:
logging.error(f"Failed to send email: {e}")
def get_boot_time():
with open("/proc/uptime", "r") as f:
uptime_seconds = int(float(f.readline().split()[0]))
boot_time = datetime.now() - timedelta(seconds=uptime_seconds) + timedelta(hours=1)
return boot_time
tmpdir = tempfile.TemporaryDirectory()
beginning = str(1000 * (int(time.time())) - (17 * 3600000))[:-3]
end = str(1000 * int(time.time()))[:-3]
urllib.request.urlretrieve("http://localhost/cacti/graph_image.php?local_graph_id=109&graph_start=" + beginning + "&graph_end=" + end + "&graph_width=700&graph_height=200", tmpdir.name + "/ping.png")
urllib.request.urlretrieve("http://localhost/cacti/graph_image.php?local_graph_id=103&graph_start=" + beginning + "&graph_end=" + end + "&graph_width=695&graph_height=198", tmpdir.name + "/traffic.png")
# Bot token and chat ID for Telegram
bot_token = "949332240:AAHNsQEmCW4it86Esa7F5o07XxwrotSM7s8"
chat_id = "-914111351"
boot_time = get_boot_time()
boot_time_str = boot_time.strftime("%d.%m.%Y, %H.%M")
subject = datetime.today().strftime('%Y-%m-%d') + ' Darmstadt'
sender_email = 'pv-tannenstr@web.de'
recipient_emails = ["tobias.siegel@outlook.com", "wsiegel@web.de"]
email_msg = create_email(sender_email, recipient_emails, subject, boot_time_str, tmpdir.name + "/traffic.png", tmpdir.name + "/ping.png")
send_email(sender_email, recipient_emails, email_msg)
try:
send_to_telegram(bot_token, chat_id, f"{subject}\nLetzter Start: {boot_time_str} Uhr", tmpdir.name + "/traffic.png", tmpdir.name + "/ping.png")
logging.info("Telegram message sent successfully.")
except ValueError as e:
logging.error(f"Failed to send images to Telegram: {e}")
tmpdir.cleanup()