postgresql 如何从命令行为 bash 自动化创建 Postgres 用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18715345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:24:11  来源:igfitidea点击:

How to create a user for Postgres from the command line for bash automation

postgresqlubuntupostgresql-9.2

提问by Tampa

I am using Ubuntu 12.04 and Postgress 9.2.

我正在使用 Ubuntu 12.04 和 Postgress 9.2。

I need to create this user with this password e.g.

我需要用这个密码创建这个用户,例如

postgres://admin:[email protected]:5432

How to do that from the command line? I need to automate with a bash script. I have a fresh install.

如何从命令行执行此操作?我需要使用 bash 脚本进行自动化。我有一个全新的安装。

回答by Tomas Greif

This will create user admin with password test101 on localhost:

这将在本地主机上创建密码为 test101 的用户 admin:

psql -c "CREATE USER admin WITH PASSWORD 'test101';"

回答by mimoralea

To run it from any user just add the sudo -u postgresto it:

要从任何用户运行它,只需sudo -u postgres向其中添加:

sudo -u postgres bash -c "psql -c \"CREATE USER vagrant WITH PASSWORD 'vagrant';\""

回答by aNj

To run it on the original docker image for example you can use the su -ccommand with the postgresuser in combination with psql:

例如,要在原始 docker 映像上运行它,您可以将su -c命令与postgres用户结合使用 psql:

su -c "psql -c \"CREATE ROLE my_user WITH LOGIN PASSWORD 'my_password' \"" postgres

回答by Iman Mirzadeh

If you are running from root, you might get an error like could not change directory to "/root": Permission denied
so it's better to run sudo with -ilike this:
sudo -i -u postgres psql -c "CREATE USER myuser WITH PASSWORD 'myuser1234';"

如果你从 root 运行,你可能会得到一个错误,could not change directory to "/root": Permission denied
所以最好像这样运行 sudo -i
sudo -i -u postgres psql -c "CREATE USER myuser WITH PASSWORD 'myuser1234';"