简体   繁体   English

如何在 Google Colab 中运行 PostgreSQL 时向“psql”命令提供密码

[英]How to supply password to 'psql' command while running PostgreSQL in Google Colab

I have installed PostgreSQL server in Google Colab as follows:我在 Google Colab 中安装了 PostgreSQL 服务器,如下所示:

# Install postgresql server
!apt update > /dev/null
!apt install postgresql > /dev/null
!service postgresql start

and have then configured the 'postgres' userid and database as follows:然后按如下方式配置“postgres”用户标识和数据库:

# Setup a password `pass` for username `postgres`
!sudo -u postgres psql -U postgres -c "ALTER USER postgres PASSWORD 'pass';"
#
# Setup a database with name `praxis` to be used
!sudo -u postgres psql -U postgres -c 'DROP DATABASE IF EXISTS praxisdb;'
!sudo -u postgres psql -U postgres -c 'CREATE DATABASE praxisdb;'

Subsequently, I have created a table, inserted data and run the select command随后,我创建了一个表,插入数据并运行 select 命令

!psql -h localhost -p 5432 -Upostgres -W -dpraxisdb -c 'create table dept ... ;'
!psql -h localhost -p 5432 -Upostgres -W -dpraxisdb -c "INSERT INTO Dept  ... ;"
!psql -h localhost -p 5432 -Upostgres -W -dpraxisdb -c "select * from dept;"

All this works perfectly but each time, I am prompted to enter the password.所有这一切都很完美,但每次都会提示我输入密码。 I wish to avoid having to enter the password each time.我希望避免每次都输入密码。 Based on what I read in the documentation on using password files, I created a file ~/.pgpass as follows:根据我在使用密码文件的文档中阅读的内容,我创建了一个文件 ~/.pgpass 如下:

!echo "localhost:5432:praxisdb:postgres:pass" > ~/.pgpass
!chmod 0600 ~/.pgpass

Now, when I execute any command, eg.现在,当我执行任何命令时,例如。

!psql -c "select * from dept;"

I get the error我得到错误

psql: error: FATAL:  role "root" does not exist

Where does this role root come from?这个角色根从何而来? I looked at the file ~/.pgpass and noted that its owner and group is root and I changed that to postgres using chown , chgrp , but that does not solve the problem.我查看了文件 ~/.pgpass 并注意到它的所有者和组是root并且我使用chownchgrp将其更改为postgres ,但这并没有解决问题。 What else should I do in this case to solve the problem.在这种情况下我还应该做什么来解决问题。

The version of Postgres and the OS is as follows: Postgres和OS的版本如下:

!sudo -u postgres psql -V
psql (PostgreSQL) 12.13 (Ubuntu 12.13-0ubuntu0.20.04.1)

You misunderstand how the password file works.您误解了密码文件的工作原理。 You still have to specify host, port, database and user in your connection request.您仍然需要在连接请求中指定主机、端口、数据库和用户。 The client library then searches the matching entry in the password file and reads the password.客户端库然后在密码文件中搜索匹配的条目并读取密码。

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

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