Python – Centos 6 – PostgresSQL9.4 – Check if PostgresSQL is installed. If not, install it and setup a Database

Script check if postgresql is installed, if it is not it will go ahead and do the appropriate checks to see if the Postgresql YUM RPM packages installed and the proceed to install PostgresSQL. It then does the post configuration steps. It can also create a database with a user assigned to it.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import psutil
import os
import subprocess
import psycopg2


def install_PostgresSQL():
    try:

        if subprocess.call(["rpm", "-q", "pgdg-centos94"]) == 0:
            print "POSTGRES-SQL IS ALREADY INSTALLED"

        elif subprocess.call(["rpm", "-q", "pgdg-centos94"]) == 1:
            subprocess.call(["yum", "localinstall", "-y", "http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-centos94-9.4-1.noarch.rpm"])
            subprocess.call(["yum", "install", "-y", "postgresql94-contrib", "postgresql94-server"])
            print "#################################################################"
            post_install_PostgreSQL()

    except Exception as e:
        print e
        print "Install failed. Exiting with Error"


def post_install_PostgreSQL():
    try:
        path = "/etc/sysconfig/pgsql/"
        fname = 'postgresql-9.4'
        ##os.chdir(path)
        full_path = os.path.join(path, fname)
        file  = open(full_path, "w")
        file.write('GDATA=/home/postgres94/pgsql/data94\nPGLOG=/home/postgres94/pgsql/pgstartup94.log')
        file.close()
        subprocess.call(["/usr/pgsql-9.4/bin/postgresql94-setup", "initdb"])
        subprocess.call(["systemctl", "enable", "postgresql-9.4"])
        subprocess.call(["systemctl", "start", "postgresql-9.4"])
        create_Database()

    except Exception as e:
        print e
        print "Error in Post Install steps"



def create_Database():
    try:
        conn = psycopg2.connect("host='10.0.0.41' dbname='postgres' user='postgres'")
        cur = conn.cursor() #Create the cursor
        #cur.execute("""SELECT * from servers""")
        conn.autocommit = True
        cur.execute("""CREATE DATABASE test""")
        cur.execute("""CREATE ROLE george WITH PASSWORD 'YourPasswordHere'""")
        cur.execute("""GRANT ALL PRIVILEGES ON DATABASE test to george""")
        #If this is not present the changes will not get commited.
        conn.commit()
        #for row in cur: #Enable the following two lines to view query results
        #    print rows
    except Exception as e:
        print e



check_PostgresSQL()
create_Database()
Share Button

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.