[英]Executing password-protected psql from python
I need to execute the following command from Python on Windows :我需要在 Windows 上从Python执行以下命令:
psql -h localhost -p 5432 -U postgres -f script.sql db_name
The above script works fine when ran from git bash / powershell.当从 git bash / powershell 运行时,上述脚本工作正常。 After entering the script in a terminal, I need to provide a password to confirm it (similar to when using
sudo
).在终端中输入脚本后,我需要提供密码进行确认(类似于使用
sudo
时)。
How can I do that?我怎样才能做到这一点? I keep finding solutions that I think are linux-based.
我一直在寻找我认为基于 linux 的解决方案。
How do I do it on Windows?我如何在 Windows 上做到这一点? I have tried many variations of solutions involving
subprocess
, ie:我尝试了许多涉及
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')
A better option (more secure) than invoking psql
with explicit mention of your password is to have a .pgpass
file as described in the docs file (and keep it protected eg chmod 600 ~/.pgpass
).比调用
psql
并明确提及您的密码更好的选择(更安全)是拥有.pgpass
文件,如 docs 文件中所述(并对其进行保护,例如chmod 600 ~/.pgpass
)。 This keeps your password out of the list of running processes.这会将您的密码排除在正在运行的进程列表之外。
On Windows:在 Windows 上:
On Microsoft Windows the file is named
%APPDATA%\postgresql\pgpass.conf
(where%APPDATA%
refers to the Application Data subdirectory in the user's profile).在 Microsoft Windows 上,该文件名为
%APPDATA%\postgresql\pgpass.conf
(其中%APPDATA%
指的是用户配置文件中的应用程序数据子目录)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.