简体   繁体   English

python 在连接到 PostgreSQL 时不能使用 .pgpass

[英]python can not use .pgpass while connecting to PostgreSQL

I can not use .pgpass file while connecting to postgresql db using python script((( My python script to connect is without password:使用 python 脚本(((我要连接的 python 脚本没有密码:

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

My .pgpass:我的.pgpass:

*:*:*:postgres:password

is located in /var/lib/postgresql - home directory for postgres user.位于/var/lib/postgresql - postgres 用户的主目录。 However when I connect to db locally:但是,当我在本地连接到 db 时:

psql -U postgres

no password is asked.不需要密码。 But for python error is raised:但是对于 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

Based on the prompt from this output: 根据此输出的提示:

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

you're running the commmand as Unix user root , so the corresponding .pgpass file must be located in root's HOME directory, which means not /var/lib/postgresql but probably /root or / 您以Unix用户root身份运行命令,因此相应的.pgpass文件必须位于root的HOME目录中,这意味着不是/var/lib/postgresql但可能是/root/

Also its permissions must be restricted to readable by the owner, that is, chmod 600 $HOME/.pgpass 此外,还必须将其权限限制为所有者可读,即chmod 600 $HOME/.pgpass

To prevent user from launching pg_dump with a permanent .pgpass or use PGPASSWORD in command, one could create .pgpass just before pg_dump starts and delete it off 3 seconds later (inside a compiled program).为了防止用户使用永久的 .pgpass 启动 pg_dump 或在命令中使用 PGPASSWORD,可以在 pg_dump 开始之前创建 .pgpass 并在 3 秒后将其删除(在已编译的程序中)。

echo 'hostname:port:database:username:password' > /home/user/.pgpass

echo 'sleep 3; rm /home/user/.pgpass; rm /home/user/remove-pgpass.sh' > /home/user/remove-pgpass.sh

chmod 600 /home/user/.pgpass

chmod +x /home/user/remove-pgpass.sh

/home/user/remove-pgpass.sh

pg_dump -h localhost -d user-db -U db-admin > mydbdump.sql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM