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/
"> /home/postgres/.bash_profile"instead of"> .bash_profile". Eventually run two commands separated by;-"cd /home/postgres ; other coomand"db_versionis already a string so you don't needstr()-db_version_short = db_version.split('.')[0]"other command ; cp /root/.bash_profile /home/postgres/.bash_profile"