【问题标题】:python can not use .pgpass while connecting to PostgreSQLpython 在连接到 PostgreSQL 时不能使用 .pgpass
【发布时间】:2021-12-10 07:09:18
【问题描述】:

在使用 python 脚本连接到 postgresql db 时,我无法使用 .pgpass 文件((( 我要连接的 python 脚本没有密码:

conn = psycopg2.connect("dbname='postgres' user='postgres' host='192.168.136.129'");

我的.pgpass:

*:*:*:postgres:password

位于 /var/lib/postgresql - postgres 用户的主目录。 但是,当我在本地连接到 db 时:

psql -U postgres

不询问密码。但是对于python会引发错误:

root@debian:/python_codes/Junior/Level1/DB1/Generator_py# python connect_db.py 
Unable to connect to db...
Traceback (most recent call last):
  File "connect_db.py", line 34, in connectdb
    conn = psycopg2.connect("dbname='postgres' user='postgres' host='192.168.136.129'");
  File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
    connection_factory=connection_factory, async=async)
OperationalError: fe_sendauth: no password supplied

【问题讨论】:

  • .pgpass 文件必须位于启动脚本的用户的主目录中。
  • 脚本在另一台服务器上启动。
  • 如果脚本确实在另一台服务器上,那么我建议您将.pgpass 文件复制到在另一台服务器上运行脚本的 UNIX 用户的主目录中。
  • 我处理了所有目录中的文件:结果相同。在本地它可以工作:不询问密码,但python脚本不起作用(((

标签: python postgresql


【解决方案1】:

根据此输出的提示:

root@debian:/python_codes/Junior/Level1/DB1/Generator_py# python connect_db.py

您以 Unix 用户 root 运行命令,因此对应的 .pgpass 文件必须位于根目录的 HOME 目录中,这意味着不是 /var/lib/postgresql 而是可能是 /root 或 /

另外它的权限必须限制为所有者可读,即chmod 600 $HOME/.pgpass

【讨论】:

    【解决方案2】:

    为了防止用户使用永久.pgpass 启动pg_dump 或在命令中使用PGPASSWORD,可以在pg_dump 启动之前创建.pgpass 并在3 秒后将其删除(在已编译的程序中)。

    subprocess.Popen(echo 'hostname:port:database:username:password' > /home/user/.pgpass, shell=True).wait()
    
    subprocess.Popen(echo 'sleep 3; rm /home/user/.pgpass; rm /home/user/remove-pgpass.sh' > /home/user/remove-pgpass.sh, shell=True).wait()
    
    subprocess.Popen(chmod 600 /home/user/.pgpass, shell=True).wait()
    
    subprocess.Popen(chmod +x /home/user/remove-pgpass.sh, shell=True).wait()
    
    subprocess.Popen(/home/user/remove-pgpass.sh, shell=True)
    
    subprocess.Popen(pg_dump -h localhost -d user-db -U db-admin > mydbdump.sql, shell=True).wait()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 2020-11-21
      • 2022-09-25
      • 1970-01-01
      • 2016-12-24
      相关资源
      最近更新 更多