skip to Main Content

So I am writing a programme in python3 which will install postgreSQL on the local host.

I am trying to configure some parameters in the .bash_profile file using the below code

import subprocess;
import os;
import pwd;

db_version = '15.0'
db_version_short = (str(db_version)).split('.')[0]

def runcmd(cmd, verbose = False, *args, **kwargs):

    process = subprocess.Popen(
        cmd,
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE,
        shell = True
    )
    std_out, std_err = process.communicate()
    if verbose:
        print((std_out.strip()).decode('utf-8'), std_err)
    pass


#########


stdoutdata = subprocess.getoutput("sudo -u postgres echo ~")
print("stdout: " + (stdoutdata.split()[0]) + 'n')
homedir = (stdoutdata.split()[0])

print(homedir)

os.chdir(homedir)

#clear contents of existing bash profile
runcmd('> .bash_profile', verbose= True)


# Define the lines to write in the .bash_profile file
bash_lines = [f"export PGDATA=/db/pgdata/{db_version_short}/data",
            f"export LD_LIBRARY_PATH=/db/pgbin/{db_version_short}/lib",
            "export PGPORT=5432",
            f"export PGSQL=/db/pgbin/pgsql/{db_version_short}",
            "PATH=$PATH:$PGSQL/bin;export PATH",
            "LANG=en_US.UTF-8; export LANG;"]

# Join the lines with line breaks
bash_command = "n".join(bash_lines)

write_command = "sudo -u postgres echo '{}' >> {}/.bash_profile".format(bash_command,homedir)

runcmd(write_command, verbose= True)

The problem I am having is that when I am running this script as root, it is trying to write to /root/.bash_profile instead of to /home/postgres/.bash_profile.

Anyone have any ideas of how I could set homedir to the postgres user’s home directory?

I tried running the script but it keeps setting homedir to /root, when I want it to be /home/postgres/

2

Answers



  1. Doing sudo -u postgres echo ~ doesn’t give your postgres’s home directory, because the ~ character is evaluated before the shell calls ‘sudo’, and of course it gets evaluated to the calling user’s home directory, root’s in this case.

    To get what you want try echo ~postgres instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search