简体   繁体   English

从 python 执行受密码保护的 psql

[英]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.

相关问题 在python中访问Windows受密码保护的文件 - Access Windows password-protected files in python 使用 python-xlswriter 或 bash 打开受密码保护的 ods 文件 - Open password-protected ods file with python-xlswriter or bash 在 Python 中使用 GMAIL API 下载受密码保护的 PDF - Downloading password-protected PDFs using GMAIL API in Python 如何在 Python (Pandas) 中引用受密码保护的 FTP 地址? - How to refer to a password-protected FTP address in Python (Pandas)? python-pptx:处理受密码保护的 PowerPoint 文件 - python-pptx: Dealing with password-protected PowerPoint files 自动解压缩 python 中受密码保护的 rar 文件 - Auto unzip of password-protected rar files in python 从受密码保护的Excel文件到pandas DataFrame - From password-protected Excel file to pandas DataFrame 使用 VS Code Python 扩展登录到受密码保护的远程 Jupyter URI(URI 中没有令牌) - use VS Code Python extension to log into remote Jupyter URI that is password-protected (no token in URI) 使用请求和HTTPBasicAuth从受密码保护的站点检索zip文件 - Using requests and HTTPBasicAuth to retrieve a zip file from a password-protected site 如何使用M2Crypto从.pem文件加载受密码保护的私钥? - How can I load a password-protected private key from a .pem file with M2Crypto?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM