{"id":59,"date":"2023-05-16T20:09:04","date_gmt":"2023-05-16T20:09:04","guid":{"rendered":"http:\/\/77interactive.com\/?p=59"},"modified":"2024-05-16T16:14:26","modified_gmt":"2024-05-16T16:14:26","slug":"python-execute-command-as-of-4-weeks-ago","status":"publish","type":"post","link":"http:\/\/77interactive.com\/?p=59","title":{"rendered":"Python &#8211; Execute command as of 4 weeks ago"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Delete backups older than 4 weeks ago<\/h2>\n\n\n\n<p>The script uses pbm delete-backup and delete-pitr to clean up backups older than 4 weeks. The script then sends an email when complete<\/p>\n\n\n\n<p>Secrets are stored in a .env file<\/p>\n\n\n\n<p>Updated version with more parameters and a comment section.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/env python3\n\n\"\"\"\npurge_mongodb_backups.py\n\nThis script does the following:\n1. Calculates the date based on the number of weeks to keep (specified by the 'weeks_to_keep' argument).\n2. Connects to MongoDB and gets the replica set name.\n3. Executes the 'pbm delete-pitr' command with a '--older-than' parameter set to the calculated date, if the 'pitr' argument is set to 1.\n4. Executes the 'pbm delete-backup' command with a '--older-than' parameter set to the calculated date, if the 'pitr' argument is set to 0.\n5. Sends an email notifying that the chosen command has been executed, the number of weeks specified to keep, and includes the replica set name in the email subject and body.\n\nThis script reads the MongoDB username and password from an external .env file.\n\nBefore running this script, make sure you have the necessary permissions to execute the commands and send emails.\nAlso, replace the placeholders in the email details section with your actual SMTP server details, email address, email password, and recipient's email address.\n\nUsage: python3 purge_mongodb_backups.py --pitr {0,1} --weeks_to_keep {1,2,3,4}\n\"\"\"\n\nimport datetime\nimport subprocess\nimport shlex\nimport argparse\nfrom dotenv import load_dotenv\nimport os\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom pymongo import MongoClient\n\n# Parse command line arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('--pitr', default=0, type=int, choices=&#91;0, 1], help='Set to 1 to delete point-in-time recovery backups, or 0 to delete regular backups.')\nparser.add_argument('--weeks_to_keep', default=4, type=int, choices=&#91;1, 2, 3, 4], help='The number of weeks to keep. Valid values are 1, 2, 3, and 4.')\nargs = parser.parse_args()\n\n# Load values from .env file\nload_dotenv()\n\n# Get the values from the .env file\nuser_name = os.getenv(\"USERNAME\")\npass_word = os.getenv(\"PASSWORD\")\n\n# Calculate the date based on the number of weeks to keep\nweeks_to_keep = args.weeks_to_keep\ndate_to_keep = (datetime.datetime.now() - datetime.timedelta(weeks=weeks_to_keep)).strftime('%Y-%m-%d')\n\n# Prepare the commands\ncmd1 = f\"pbm delete-pitr -f --older-than {date_to_keep} --mongodb-uri='mongodb:\/\/{user_name}:{pass_word}@localhost:27017\/admin?authSource=admin'\"\ncmd2 = f\"pbm delete-backup -f --older-than {date_to_keep} --mongodb-uri='mongodb:\/\/{user_name}:{pass_word}@localhost:27017\/admin?authSource=admin'\"\ncmd1 = shlex.split(cmd1)\ncmd2 = shlex.split(cmd2)\n\n# Execute the chosen command\nif args.pitr == 1:\n    subprocess.run(cmd1, check=True)\nelif args.pitr == 0:\n    subprocess.run(cmd2, check=True)\n\n# Connect to MongoDB and get replica set name\nclient = MongoClient(f'mongodb:\/\/{user_name}:{pass_word}@localhost:27017\/admin?authSource=admin')\nreplica_set_name = client.admin.command(\"isMaster\")&#91;\"setName\"]\n\n# Email details\nsmtp_server = 'smtp.yourserver.com'\nsmtp_port = 587  # or 465 if your server uses SSL\nemail_address = 'your_email_address'\nemail_password = 'your_email_password'\nrecipient_email = 'recipient_email_address'\n\n# Email content\nmsg = MIMEText(f'The chosen command has been executed successfully on replica set: {replica_set_name}. The number of weeks to keep is: {weeks_to_keep}.')\nmsg&#91;'Subject'] = f'Command Execution Notification for {replica_set_name}'\nmsg&#91;'From'] = email_address\nmsg&#91;'To'] = recipient_email\n\n# Send the email\ns = smtplib.SMTP(smtp_server, smtp_port)\ns.starttls()  # comment this line if your server uses SSL\ns.login(email_address, email_password)\ns.sendmail(email_address, &#91;recipient_email], msg.as_string())\ns.quit()\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">The .env file<\/h2>\n\n\n\n<p>The environment file is of the following format<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>USERNAME=yourusername\nPASSWORD=yourpassword<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Original version:<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import datetime\nimport subprocess\nimport shlex\nfrom dotenv import load_dotenv\nimport os\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom pymongo import MongoClient\n\n# Load values from .env file\nload_dotenv()\n\n# Get the values from the .env file\nuser_name = os.getenv(\"USERNAME\")\npass_word = os.getenv(\"PASSWORD\")\n\n# Calculate the date four weeks ago\nfour_weeks_ago = (datetime.datetime.now() - datetime.timedelta(weeks=4)).strftime('%Y-%m-%d')\n\n# Prepare the first command\ncmd1 = f\"pbm delete-pitr -f --older-than {four_weeks_ago} --mongodb-uri='mongodb:\/\/{user_name}:{pass_word}@localhost:27017\/admin?authSource=admin'\"\n\n# Prepare the second command\ncmd2 = f\"pbm delete-backup -f --older-than {four_weeks_ago} --mongodb-uri='mongodb:\/\/{user_name}:{pass_word}@localhost:27017\/admin?authSource=admin'\"\n\n# Use shlex to handle spaces in commands properly\ncmd1 = shlex.split(cmd1)\ncmd2 = shlex.split(cmd2)\n\n# Execute the first command\nsubprocess.run(cmd1, check=True)\n\n# Execute the second command\nsubprocess.run(cmd2, check=True)\n\n# Connect to MongoDB and get replica set name\nclient = MongoClient(f'mongodb:\/\/{user_name}:{pass_word}@localhost:27017\/admin?authSource=admin')\nreplica_set_name = client.admin.command(\"isMaster\")&#91;\"setName\"]\n\n# Email details\nsmtp_server = 'smtp.yourserver.com'\nsmtp_port = 587  # or 465 if your server uses SSL\nemail_address = 'your_email_address'\nemail_password = 'your_email_password'\nrecipient_email = 'recipient_email_address'\n\n# Email content\nmsg = MIMEText(f'Both commands have been executed successfully on replica set: {replica_set_name}.')\nmsg&#91;'Subject'] = f'Command Execution Notification for {replica_set_name}'\nmsg&#91;'From'] = email_address\nmsg&#91;'To'] = recipient_email\n\n# Send the email\ns = smtplib.SMTP(smtp_server, smtp_port)\ns.starttls()  # comment this line if your server uses SSL\ns.login(email_address, email_password)\ns.sendmail(email_address, &#91;recipient_email], msg.as_string())\ns.quit()\n\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Delete backups older than 4 weeks ago The script uses pbm delete-backup and delete-pitr to clean up backups older than 4 weeks. The script then sends an email when complete Secrets are stored in a .env file Updated version with more parameters and a comment section. The .env file The environment file is of the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[10,3],"class_list":["post-59","post","type-post","status-publish","format-standard","hentry","category-python","tag-backup","tag-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python - Execute command as of 4 weeks ago - 77 Interactive<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"http:\/\/77interactive.com\/?p=59\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python - Execute command as of 4 weeks ago - 77 Interactive\" \/>\n<meta property=\"og:description\" content=\"Delete backups older than 4 weeks ago The script uses pbm delete-backup and delete-pitr to clean up backups older than 4 weeks. The script then sends an email when complete Secrets are stored in a .env file Updated version with more parameters and a comment section. The .env file The environment file is of the [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"http:\/\/77interactive.com\/?p=59\" \/>\n<meta property=\"og:site_name\" content=\"77 Interactive\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-16T20:09:04+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-05-16T16:14:26+00:00\" \/>\n<meta name=\"author\" content=\"Rudy\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Rudy\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"http:\/\/77interactive.com\/?p=59#article\",\"isPartOf\":{\"@id\":\"http:\/\/77interactive.com\/?p=59\"},\"author\":{\"name\":\"Rudy\",\"@id\":\"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9\"},\"headline\":\"Python &#8211; Execute command as of 4 weeks ago\",\"datePublished\":\"2023-05-16T20:09:04+00:00\",\"dateModified\":\"2024-05-16T16:14:26+00:00\",\"mainEntityOfPage\":{\"@id\":\"http:\/\/77interactive.com\/?p=59\"},\"wordCount\":65,\"keywords\":[\"backup\",\"python\"],\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"http:\/\/77interactive.com\/?p=59\",\"url\":\"http:\/\/77interactive.com\/?p=59\",\"name\":\"Python - Execute command as of 4 weeks ago - 77 Interactive\",\"isPartOf\":{\"@id\":\"http:\/\/77interactive.com\/#website\"},\"datePublished\":\"2023-05-16T20:09:04+00:00\",\"dateModified\":\"2024-05-16T16:14:26+00:00\",\"author\":{\"@id\":\"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9\"},\"breadcrumb\":{\"@id\":\"http:\/\/77interactive.com\/?p=59#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"http:\/\/77interactive.com\/?p=59\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"http:\/\/77interactive.com\/?p=59#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/77interactive.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python &#8211; Execute command as of 4 weeks ago\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/77interactive.com\/#website\",\"url\":\"http:\/\/77interactive.com\/\",\"name\":\"77 Interactive\",\"description\":\"Rudy&#039;s Code snippets\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/77interactive.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9\",\"name\":\"Rudy\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/77interactive.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/e336b9aecd39b40691ff8ccfcd68506415072dbe8caffc0485b94a1bc22b774d?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/e336b9aecd39b40691ff8ccfcd68506415072dbe8caffc0485b94a1bc22b774d?s=96&d=mm&r=g\",\"caption\":\"Rudy\"},\"url\":\"http:\/\/77interactive.com\/?author=1\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python - Execute command as of 4 weeks ago - 77 Interactive","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"http:\/\/77interactive.com\/?p=59","og_locale":"en_US","og_type":"article","og_title":"Python - Execute command as of 4 weeks ago - 77 Interactive","og_description":"Delete backups older than 4 weeks ago The script uses pbm delete-backup and delete-pitr to clean up backups older than 4 weeks. The script then sends an email when complete Secrets are stored in a .env file Updated version with more parameters and a comment section. The .env file The environment file is of the [&hellip;]","og_url":"http:\/\/77interactive.com\/?p=59","og_site_name":"77 Interactive","article_published_time":"2023-05-16T20:09:04+00:00","article_modified_time":"2024-05-16T16:14:26+00:00","author":"Rudy","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Rudy","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"http:\/\/77interactive.com\/?p=59#article","isPartOf":{"@id":"http:\/\/77interactive.com\/?p=59"},"author":{"name":"Rudy","@id":"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9"},"headline":"Python &#8211; Execute command as of 4 weeks ago","datePublished":"2023-05-16T20:09:04+00:00","dateModified":"2024-05-16T16:14:26+00:00","mainEntityOfPage":{"@id":"http:\/\/77interactive.com\/?p=59"},"wordCount":65,"keywords":["backup","python"],"articleSection":["Python"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"http:\/\/77interactive.com\/?p=59","url":"http:\/\/77interactive.com\/?p=59","name":"Python - Execute command as of 4 weeks ago - 77 Interactive","isPartOf":{"@id":"http:\/\/77interactive.com\/#website"},"datePublished":"2023-05-16T20:09:04+00:00","dateModified":"2024-05-16T16:14:26+00:00","author":{"@id":"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9"},"breadcrumb":{"@id":"http:\/\/77interactive.com\/?p=59#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["http:\/\/77interactive.com\/?p=59"]}]},{"@type":"BreadcrumbList","@id":"http:\/\/77interactive.com\/?p=59#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/77interactive.com\/"},{"@type":"ListItem","position":2,"name":"Python &#8211; Execute command as of 4 weeks ago"}]},{"@type":"WebSite","@id":"http:\/\/77interactive.com\/#website","url":"http:\/\/77interactive.com\/","name":"77 Interactive","description":"Rudy&#039;s Code snippets","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/77interactive.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9","name":"Rudy","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/77interactive.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/e336b9aecd39b40691ff8ccfcd68506415072dbe8caffc0485b94a1bc22b774d?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/e336b9aecd39b40691ff8ccfcd68506415072dbe8caffc0485b94a1bc22b774d?s=96&d=mm&r=g","caption":"Rudy"},"url":"http:\/\/77interactive.com\/?author=1"}]}},"_links":{"self":[{"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/posts\/59","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=59"}],"version-history":[{"count":0,"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/posts\/59\/revisions"}],"wp:attachment":[{"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=59"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=59"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=59"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}