【问题标题】:Executing password-protected psql from python从 python 执行受密码保护的 psql
【发布时间】:2020-12-07 19:09:45
【问题描述】:

我需要在 Windows 上从 Python 执行以下命令:

psql -h localhost -p 5432 -U postgres -f script.sql db_name

从 git bash / powershell 运行时,上述脚本运行良好。在终端输入脚本后,需要提供密码进行确认(类似于使用sudo时)。

我该怎么做?我一直在寻找我认为基于 linux 的解决方案。

如何在 Windows 上执行此操作?我尝试了许多涉及subprocess 的解决方案变体,即:

import subprocess

p2 = subprocess.Popen(
    'psql -h localhost -p 5432 -U postgres -f script.sql db_name',
    stdin=subprocess.PIPE,
    stderr=subprocess.PIPE,
    universal_newlines=True)

print('this will print')
sudo_prompt = p2.communicate('THE_PASSWORD' + '\n')[1]
print('this will not')

【问题讨论】:

  • 只需在子进程调用前设置环境变量PGPASSWORD
  • 这似乎不起作用,即使我在执行 psql 从终端本身之前执行set PGPASSWORD=THE_PASSWORD。

标签: python psql


【解决方案1】:

比调用psql 并明确提及您的密码更好的选择(更安全)是拥有一个.pgpass file as described in the docs 文件(并对其进行保护,例如chmod 600 ~/.pgpass)。这会将您的密码排除在正在运行的进程列表之外。

在 Windows 上:

在 Microsoft Windows 上,该文件名为 %APPDATA%\postgresql\pgpass.conf(其中 %APPDATA% 是指用户配置文件中的应用程序数据子目录)。

【讨论】:

  • 没关系:思路一样,只是位置不同(见文档链接)
猜你喜欢
  • 2015-07-13
  • 2020-06-18
  • 1970-01-01
  • 2011-12-23
  • 2016-08-19
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
相关资源
最近更新 更多