sudo su - postgres 和 sudo -u postgres 有什么区别?

Cra*_*ger 47 postgresql su shell sudo

PostgreSQL 用户默认在 unix 套接字上进行对等身份验证,其中 unix 用户必须与 PostgreSQL 用户相同。所以人们经常使用susudo成为postgres超级用户。

我经常看到人们使用以下结构:

sudo su - postgres
Run Code Online (Sandbox Code Playgroud)

而不是

sudo -u postgres -i
Run Code Online (Sandbox Code Playgroud)

我想知道为什么。同样,我见过:

sudo su - postgres -c psql
Run Code Online (Sandbox Code Playgroud)

代替

sudo -u postgres psql
Run Code Online (Sandbox Code Playgroud)

如果没有领导sudosu版本可能会做出一些感觉,如果你是一个老平台没有sudo。但是为什么要在比史前时代更短的 UNIX 或 Linux 上使用sudo su

Cra*_*ger 51

忘记 sudo su

使用 没有任何好处sudo su,这是人们习惯使用su. sudo当 Linux 发行版停止设置 root 密码并成为sudo访问 root 帐户的唯一方法时,人们开始站在前面。与其改变他们的习惯,他们只是使用sudo su. (我是其中之一,直到最近使用带有sudoers配置的迫使我改变我的习惯)。

sudo -u

对于登录 shell,sudo -u postgres -isudo su - postgres. 它不需要用户在 中具有 root 访问权限/etc/sudoers,他们只需要成为用户的权限postgres。它还可以让您实施更好的访问控制。

用于命令执行

sudo -u postgres psql -c "SELECT 1"
Run Code Online (Sandbox Code Playgroud)

优于替代方案:

sudo su - postgres -c "psql -c \"SELECT 1\""
Run Code Online (Sandbox Code Playgroud)

因为您不必双重转义引号和其他 shell 元字符以及不需要 root 的其他安全优势。你可能会不小心写到:

sudo su - postgres -c psql -c "SELECT 1"
Run Code Online (Sandbox Code Playgroud)

有时,这将无法正常工作。

最后,通过sudo例如设置环境变量更容易

sudo PATH=/usr/pgsql-9.3/bin:$PATH -u postgres /usr/pgsql-9.3/bin/initdb -D /var/lib/pgsql/testcluster
Run Code Online (Sandbox Code Playgroud)

比通过su。(在这里,PATH需要设置,以便initdb可以找到正确的postgres可执行文件)。

所以。忘记su命令存在。你不再需要它了。要打破这个习惯,请将其别名为会打印错误的内容。(一些 init 和 package setup 脚本仍在使用,su所以你不能删除它,但是)。

也可以看看: