0

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/

4
  • maybe use "> /home/postgres/.bash_profile" instead of "> .bash_profile". Eventually run two commands separated by ; - "cd /home/postgres ; other coomand" Commented Apr 23, 2024 at 11:01
  • db_version is already a string so you don't need str() - db_version_short = db_version.split('.')[0] Commented Apr 23, 2024 at 11:05
  • you may also use two commands "other command ; cp /root/.bash_profile /home/postgres/.bash_profile" Commented Apr 23, 2024 at 11:07
  • You have homedir already, use it Commented Apr 23, 2024 at 15:47

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.