尝试从以 root 身份运行的 python 脚本写入 postgres 用户的 .bash_profile

问题描述 投票:0回答:1

所以我正在用 python3 编写一个程序,它将在本地主机上安装 postgreSQL。

我正在尝试使用以下代码在 .bash_profile 文件中配置一些参数

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)

我遇到的问题是,当我以 root 身份运行此脚本时,它试图写入 /root/.bash_profile 而不是 /home/postgres/.bash_profile。

有人知道如何将 homedir 设置为 postgres 用户的主目录吗?

我尝试运行脚本,但当我希望它是 /home/postgres/ 时,它一直将 homedir 设置为 /root

python postgresql bash
1个回答
0
投票

执行

sudo -u postgres echo ~
不会给出 postgres 的主目录,因为 ~ 字符是在 shell 调用“sudo”之前评估的,当然在这种情况下它会评估到调用用户的主目录根目录。为了得到你想要的,尝试
echo ~postgres

© www.soinside.com 2019 - 2024. All rights reserved.