简体   繁体   中英

Why am I getting peer authentication failed error when trying to connect using psycopg2?

So I have a successful install of Postgres on Ubuntu and am trying to do some basic connection and creating a table in a db using another username other than the default (postgres) and coming up short. From what I can gather I think it may have something to do with permissions? What I want is to be able to use some superuser other than postgres to create tables and do stuff.

"psql example3" and "\l" shows the example3 db was created successfully. I now have a list of databases include the default postgres, template0, template1 and example3 all with owner as postgres. What I run into problems then is running demoscript.py gives a fatal "peer authentication failed for user 'thisuser'"

#Create the db and user with superuser permissions
sudo -u postgres -i
createdb example3
createuser --interactive --pwprompt
#role:thisuser
#pwd:thispass
#superuser?:Y
#demoscript.py
import psycopg2 
connection = psycopg2.connect('dbname=example3 user=thisuser password=thispass')
cursor = connection.cursor()
cursor.execute('DROP TABLE IF EXISTS todos;')

cursor.execute('''
    CREATE TABLE todos(
        id serial PRIMARY KEY,
        description VARCHAR NOT NULL
        );
''')
connection.commit()
cursor.close()
connection.close()

Expected result is that the todos table should show as created after looking for it in the example3 db. But I just get the fatal error.

When you don't specify a host in your connection, it tries to connect via Unix sockets. By default, PostgreSQL is set up to use peer authentication on those, which means it compares the PostgreSQL username to the currently logged in OS user. If you change your connection to:

connection = psycopg2.connect('dbname=example3 user=thisuser password=thispass host=localhost')

that should cause it to use the authentication settings for TCP/IP connections, which default to password authentication on most systems I've used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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