{"id":305,"date":"2024-02-21T15:21:02","date_gmt":"2024-02-21T15:21:02","guid":{"rendered":"http:\/\/77interactive.com\/?p=305"},"modified":"2024-02-22T04:08:17","modified_gmt":"2024-02-22T04:08:17","slug":"postgresql-pg_dump-backups-via-python","status":"publish","type":"post","link":"http:\/\/77interactive.com\/?p=305","title":{"rendered":"PostgreSQL pg_dump backups via Python"},"content":{"rendered":"\n<p>The following scripts backup your PostgreSQL databases via Python using pg_dump. The scripts will then compress the backup via zip. These backup scripts are linux specific.<\/p>\n\n\n\n<p>You&#8217;ll have to manage secrets either using a .pgpass file or environment variables. This is the first pass before using any type of password security.<\/p>\n\n\n\n<pre class=\"wp-block-code has-cyan-bluish-gray-background-color has-background\"><code>import subprocess\r\nimport psycopg2\r\nfrom datetime import datetime\r\nimport os\r\n\r\n# PostgreSQL connection parameters\r\ndb_params = {\r\n    \"dbname\": \"postgres\",  # change to your database name if different\r\n    \"user\": \"your_username\",\r\n    \"password\": \"your_password\",\r\n    \"host\": \"localhost\"\r\n}\r\n\r\n# Directory to store the backups\r\nbackup_dir = \"\/mnt\/backups\/\"\r\nos.makedirs(backup_dir, exist_ok=True)\r\n\r\ndef get_databases(connection_parameters):\r\n    \"\"\"Retrieve a list of database names.\"\"\"\r\n    conn = None\r\n    databases = &#91;]\r\n    try:\r\n        conn = psycopg2.connect(**connection_parameters)\r\n        cur = conn.cursor()\r\n        cur.execute(\"SELECT datname FROM pg_database WHERE datistemplate = false;\")\r\n        databases = &#91;db&#91;0] for db in cur.fetchall()]\r\n        cur.close()\r\n    except (Exception, psycopg2.DatabaseError) as error:\r\n        print(error)\r\n    finally:\r\n        if conn is not closed:\r\n            conn.close()\r\n    return databases\r\n\r\ndef backup_database(db_name, backup_directory):\r\n    \"\"\"Backup a single database and zip the backup file.\"\"\"\r\n    current_date = datetime.now().strftime('%Y%m%d')\r\n    backup_file = os.path.join(backup_directory, f\"{db_name}.sql\")\r\n    zip_file = f\"{current_date}-{db_name}.zip\"\r\n    \r\n    # Backup database to SQL file\r\n    subprocess.run(f\"pg_dump -U {db_params&#91;'user']} -w {db_name} > {backup_file}\", shell=True, check=True)\r\n    \r\n    # Compress the SQL file\r\n    subprocess.run(f\"zip -j {backup_dir}{zip_file} {backup_file}\", shell=True, check=True)\r\n    \r\n    # Remove the original SQL file\r\n    os.remove(backup_file)\r\n\r\nif __name__ == \"__main__\":\r\n    databases = get_databases(db_params)\r\n    for db_name in databases:\r\n        print(f\"Backing up database: {db_name}\")\r\n        backup_database(db_name, backup_dir)\r\n    print(\"Backup process completed.\")\r\n<\/code><\/pre>\n\n\n\n<p>Alternative version that I&#8217;ve used before<\/p>\n\n\n\n<pre class=\"wp-block-code has-cyan-bluish-gray-background-color has-background\"><code>import os\nimport datetime\nimport subprocess\n\n# Database connection details\n\nHOST = \"localhost\"\nPORT = 5432\nUSER = \"postgres\"\nPASSWORD = \"your_password\"  # Replace with your actual password\n\n# Backup directory\n\nBACKUP_DIR = \"\/mnt\/backups\/\"\n\n# Get current date in YYYYMMDD format\n\ncurrent_date = datetime.datetime.now().strftime(\"%Y%m%d\")\n\n\ndef main():\n    # Connect to PostgreSQL server\n\n    try:\n        conn = psycopg2.connect(host=HOST, port=PORT, user=USER, password=PASSWORD)\n    except psycopg2.Error as e:\n        print(\"Error connecting to database:\", e)\n        return\n    # Get all databases except system ones\n\n    try:\n        cur = conn.cursor()\n        cur.execute(\n            \"SELECT datname FROM pg_database WHERE datistemplate = false AND datname NOT IN ('postgres', 'template')\"\n        )\n        databases = &#91;row&#91;0] for row in cur.fetchall()]\n    except psycopg2.Error as e:\n        print(\"Error fetching databases:\", e)\n        return\n    # Backup each database\n\n    for db in databases:\n        backup_database(db)\n    # Close connection\n\n    conn.close()\n\n\ndef backup_database(db_name):\n    # Dump database\n\n    dump_file = os.path.join(BACKUP_DIR, f\"{db_name}.sql\")\n    command = &#91;\n        \"pg_dump\",\n        \"-h\",\n        HOST,\n        \"-p\",\n        str(PORT),\n        \"-U\",\n        USER,\n        \"-d\",\n        db_name,\n        \">\",\n        dump_file,\n    ]\n    subprocess.run(command, check=True)\n\n    # Zip the dump\n\n    zip_file = os.path.join(BACKUP_DIR, f\"{current_date}-{db_name}.zip\")\n    subprocess.run(&#91;\"zip\", \"-r\", zip_file, dump_file], check=True)\n\n    # Remove the uncompressed dump\n\n    os.remove(dump_file)\n\n\nif __name__ == \"__main__\":\n    main()\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>The following scripts backup your PostgreSQL databases via Python using pg_dump. The scripts will then compress the backup via zip. These backup scripts are linux specific. You&#8217;ll have to manage secrets either using a .pgpass file or environment variables. This is the first pass before using any type of password security. Alternative version that I&#8217;ve [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":307,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[21,46,2],"tags":[17,18,3],"class_list":["post-305","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-postgres","category-postgresql","category-python","tag-postgres","tag-postgresql","tag-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>PostgreSQL pg_dump backups via Python - 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=305\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PostgreSQL pg_dump backups via Python - 77 Interactive\" \/>\n<meta property=\"og:description\" content=\"The following scripts backup your PostgreSQL databases via Python using pg_dump. The scripts will then compress the backup via zip. These backup scripts are linux specific. You&#8217;ll have to manage secrets either using a .pgpass file or environment variables. This is the first pass before using any type of password security. Alternative version that I&#8217;ve [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"http:\/\/77interactive.com\/?p=305\" \/>\n<meta property=\"og:site_name\" content=\"77 Interactive\" \/>\n<meta property=\"article:published_time\" content=\"2024-02-21T15:21:02+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-02-22T04:08:17+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/77interactive.com\/wp-content\/uploads\/2024\/02\/Bearbackup001-Wide-1024x576.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1024\" \/>\n\t<meta property=\"og:image:height\" content=\"576\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\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=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"http:\/\/77interactive.com\/?p=305#article\",\"isPartOf\":{\"@id\":\"http:\/\/77interactive.com\/?p=305\"},\"author\":{\"name\":\"Rudy\",\"@id\":\"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9\"},\"headline\":\"PostgreSQL pg_dump backups via Python\",\"datePublished\":\"2024-02-21T15:21:02+00:00\",\"dateModified\":\"2024-02-22T04:08:17+00:00\",\"mainEntityOfPage\":{\"@id\":\"http:\/\/77interactive.com\/?p=305\"},\"wordCount\":66,\"image\":{\"@id\":\"http:\/\/77interactive.com\/?p=305#primaryimage\"},\"thumbnailUrl\":\"http:\/\/77interactive.com\/wp-content\/uploads\/2024\/02\/Bearbackup001-Wide.png\",\"keywords\":[\"postgres\",\"postgresql\",\"python\"],\"articleSection\":[\"postgres\",\"PostgreSQL\",\"Python\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"http:\/\/77interactive.com\/?p=305\",\"url\":\"http:\/\/77interactive.com\/?p=305\",\"name\":\"PostgreSQL pg_dump backups via Python - 77 Interactive\",\"isPartOf\":{\"@id\":\"http:\/\/77interactive.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"http:\/\/77interactive.com\/?p=305#primaryimage\"},\"image\":{\"@id\":\"http:\/\/77interactive.com\/?p=305#primaryimage\"},\"thumbnailUrl\":\"http:\/\/77interactive.com\/wp-content\/uploads\/2024\/02\/Bearbackup001-Wide.png\",\"datePublished\":\"2024-02-21T15:21:02+00:00\",\"dateModified\":\"2024-02-22T04:08:17+00:00\",\"author\":{\"@id\":\"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9\"},\"breadcrumb\":{\"@id\":\"http:\/\/77interactive.com\/?p=305#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"http:\/\/77interactive.com\/?p=305\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/77interactive.com\/?p=305#primaryimage\",\"url\":\"http:\/\/77interactive.com\/wp-content\/uploads\/2024\/02\/Bearbackup001-Wide.png\",\"contentUrl\":\"http:\/\/77interactive.com\/wp-content\/uploads\/2024\/02\/Bearbackup001-Wide.png\",\"width\":1820,\"height\":1024},{\"@type\":\"BreadcrumbList\",\"@id\":\"http:\/\/77interactive.com\/?p=305#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/77interactive.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"PostgreSQL pg_dump backups via Python\"}]},{\"@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":"PostgreSQL pg_dump backups via Python - 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=305","og_locale":"en_US","og_type":"article","og_title":"PostgreSQL pg_dump backups via Python - 77 Interactive","og_description":"The following scripts backup your PostgreSQL databases via Python using pg_dump. The scripts will then compress the backup via zip. These backup scripts are linux specific. You&#8217;ll have to manage secrets either using a .pgpass file or environment variables. This is the first pass before using any type of password security. Alternative version that I&#8217;ve [&hellip;]","og_url":"http:\/\/77interactive.com\/?p=305","og_site_name":"77 Interactive","article_published_time":"2024-02-21T15:21:02+00:00","article_modified_time":"2024-02-22T04:08:17+00:00","og_image":[{"width":1024,"height":576,"url":"http:\/\/77interactive.com\/wp-content\/uploads\/2024\/02\/Bearbackup001-Wide-1024x576.png","type":"image\/png"}],"author":"Rudy","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Rudy","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"http:\/\/77interactive.com\/?p=305#article","isPartOf":{"@id":"http:\/\/77interactive.com\/?p=305"},"author":{"name":"Rudy","@id":"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9"},"headline":"PostgreSQL pg_dump backups via Python","datePublished":"2024-02-21T15:21:02+00:00","dateModified":"2024-02-22T04:08:17+00:00","mainEntityOfPage":{"@id":"http:\/\/77interactive.com\/?p=305"},"wordCount":66,"image":{"@id":"http:\/\/77interactive.com\/?p=305#primaryimage"},"thumbnailUrl":"http:\/\/77interactive.com\/wp-content\/uploads\/2024\/02\/Bearbackup001-Wide.png","keywords":["postgres","postgresql","python"],"articleSection":["postgres","PostgreSQL","Python"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"http:\/\/77interactive.com\/?p=305","url":"http:\/\/77interactive.com\/?p=305","name":"PostgreSQL pg_dump backups via Python - 77 Interactive","isPartOf":{"@id":"http:\/\/77interactive.com\/#website"},"primaryImageOfPage":{"@id":"http:\/\/77interactive.com\/?p=305#primaryimage"},"image":{"@id":"http:\/\/77interactive.com\/?p=305#primaryimage"},"thumbnailUrl":"http:\/\/77interactive.com\/wp-content\/uploads\/2024\/02\/Bearbackup001-Wide.png","datePublished":"2024-02-21T15:21:02+00:00","dateModified":"2024-02-22T04:08:17+00:00","author":{"@id":"http:\/\/77interactive.com\/#\/schema\/person\/0e61d2a984b8304618026b207e6121e9"},"breadcrumb":{"@id":"http:\/\/77interactive.com\/?p=305#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["http:\/\/77interactive.com\/?p=305"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/77interactive.com\/?p=305#primaryimage","url":"http:\/\/77interactive.com\/wp-content\/uploads\/2024\/02\/Bearbackup001-Wide.png","contentUrl":"http:\/\/77interactive.com\/wp-content\/uploads\/2024\/02\/Bearbackup001-Wide.png","width":1820,"height":1024},{"@type":"BreadcrumbList","@id":"http:\/\/77interactive.com\/?p=305#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/77interactive.com\/"},{"@type":"ListItem","position":2,"name":"PostgreSQL pg_dump backups via Python"}]},{"@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\/305","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=305"}],"version-history":[{"count":0,"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/posts\/305\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=\/wp\/v2\/media\/307"}],"wp:attachment":[{"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=305"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=305"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/77interactive.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=305"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}