1
0
Fork 0
scripts/sysadmin/backup_summary.py
Luca Beltrame c4f7279f2e
Restructure directory layout
To make this better than the unorganized mess it used to be.
2021-01-03 15:26:29 +01:00

76 lines
1.9 KiB
Python

#!/usr/bin/python3
from email.message import EmailMessage
from email.utils import formatdate
import smtplib
import sarge
import json
from datetime import datetime, timedelta
TEMPLATE="""
Hello,
as of today, {num_backups} backups have been made this week:
{content}
Only successful backups are listed.
--
Automated notification system
"""
def find_range(array):
sorted_array = sorted(array["archives"],
key=lambda x: datetime.strptime(x["time"],"%Y-%m-%dT%H:%M:%S.%f"),
reverse=True)
last_time = datetime.strptime(sorted_array[0]["time"],
"%Y-%m-%dT%H:%M:%S.%f")
for idx, record in reversed(list(enumerate(sorted_array))):
if record == sorted_array[0]:
break
first_time = datetime.strptime(record["time"], "%Y-%m-%dT%H:%M:%S.%f")
monday1 = (first_time - timedelta(days=first_time.weekday()))
monday2 = (last_time - timedelta(days=last_time.weekday()))
weeks = (monday2 - monday1).days / 7
if weeks <= 1:
break
return [item["archive"] for item in sorted_array[0: idx + 1]]
def create_message(data):
content = "\n".join("* {}".format(item) for item in data)
complete_message = TEMPLATE.format(num_backups=len(data),
content=content)
msg = EmailMessage()
msg.set_content(complete_message)
msg["Subject"] = "Weekly backup report"
msg["From"] = "Notification system <replaceme>"
msg["To"] = "Mr.X <replaceme>"
msg["Date"] = formatdate(localtime=True)
msg.set_param("charset", "UTF-8")
msg.replace_header("Content-Transfer-Encoding", "8bit")
return msg
def main():
borgmatic_data = sarge.get_stdout(
"borgmatic list --last 10 --json --successful")
borgmatic_data = json.loads(borgmatic_data)
contents = find_range(borgmatic_data[0])
msg = create_message(contents)
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
if __name__ == "__main__":
main()