fbpx

Python Script to Take PostgreSQL Backup

Here is a simple Python script that you can use to take a backup of a PostgreSQL database

				
					import os
import time

# Database details
DB_HOST = 'localhost'
DB_USER = 'your_username'
DB_PASS = 'your_password'
DB_NAME = 'your_database_name'

# Backup details
BACKUP_PATH = '/path/to/backup/location'
TIMESTAMP = time.strftime('%Y-%m-%d-%H-%M-%S')
BACKUP_FILE = DB_NAME + '_' + TIMESTAMP + '.sql'

# Command to take a backup
BACKUP_CMD = "pg_dump -h {0} -U {1} -d {2} > {3}".format(DB_HOST, DB_USER, DB_NAME, os.path.join(BACKUP_PATH, BACKUP_FILE))

# Execute the backup command
os.system(BACKUP_CMD)

				
			

This script will create a .sql file in the BACKUP_PATH location with the current timestamp in the file name. You can customize the script as per your requirements, such as scheduling it to run automatically at regular intervals.

Note: This script assumes that you have already installed the pg_dump utility on your system and it is available in your PATH environment variable. You can check if the pg_dump utility is installed by running the following command in a terminal.

If the pg_dump utility is not installed, you can install it using the following command (on Ubuntu):

				
					sudo apt-get install postgresql-client

				
			

Share:

Facebook
Twitter
Pinterest
LinkedIn

Social Media

Most Popular

Get The Latest Updates

Subscribe To Our Weekly Newsletter

No spam, notifications only about new products, updates.

Categories