btald1331
btald1331

Reputation: 597

PostgreSQL and Python: Automated Password change

I've been trying to automate the installation of an Open Street Map Server since no one has published one yet and the task is pretty tedious. In order to do this I'm dealing with PostgreSQL databases in a script, which I left Python in charge of.

Here's the situation: Basically I'm running python scripts dealing with the database throughout bash code. I'm trying to make the install as user friendly as possible, part of that is automating the PostgreSQL setup. I prompt the user, in bash, for a password they would like to use for the postgres database that already comes with PostgreSQL. I then send their password as a command line argument to a Python script.

This is the part of the script I'm having problems with:

import psycopg2
import sys


con = None
code = sys.argv[1]

try:

    con = psycopg2.connect(database='postgres', user='postgres')

    cur = con.cursor()
    cur.execute("ALTER USER postgres WITH PASSWORD '%s'" % code)

Basically: On the bottom line where I change the password for the postgres database, it doesn't actually work. I know this because later I am prompted in my bash script to enter the password and it results in an authentication failure.

I'm pretty new to this, so if anyone has some good advice, it would be greatly appreciated.

Upvotes: 4

Views: 1410

Answers (1)

Please use the below code, you can generate random passwords and update them NOTE: For this code to work, the readwrite1 user has to be present in database prior using this

from psycopg2 import Error
import psycopg2
import random    
#password generation
def password_generator(password_length):
    # maximum length of password needed
    characters = string.ascii_letters + string.digits + '!@#$%^&*()'
    password = ''.join(random.choice(characters) for i in range(password_length))
    return password


#define a function that handles and parses psycopg2 exceptions
def print_psycopg2_exception(err):
    err_type, err_obj, traceback = sys.exc_info()

    # get the line number when exception occured
    line_num = traceback.tb_lineno
    # print the connect() error
    print ("\npsycopg2 ERROR:", err, "on line number:", line_num)
    print ("psycopg2 traceback:", traceback, "-- type:", err_type)

    # psycopg2 extensions.Diagnostics object attribute
    print ("\nextensions.Diagnostics:", err.diag)

    # print the pgcode and pgerror exceptions
    print ("pgerror:", err.pgerror)
    print ("pgcode:", err.pgcode, "\n")

def update_password():
    password=password_generator(10)
    try:
        con = psycopg2.connect(host="host here",database="dbhere", user="username",password="password")
        cur = con.cursor()
        cur.execute("alter user readwrite1 with password %(password)s;", {'password': password})
        con.commit()
    except Exception as err:
        # pass exception to function
        print_psycopg2_exception(err)
        exit(1)
    finally:
        print('password is: ', password)
        if con:
            con.close()
    return password

Upvotes: 1

Related Questions