简体   繁体   English

Bash脚本:从shell脚本登录到postgres主页

[英]Bash script : Login to postgres home from shell script

I have to take a data dump from my postgres database. 我必须从我的postgres数据库中获取数据转储。

How do I log in to the postgres home ? 我如何登录postgres主页? . I have the following script but it doesn't work : 我有以下脚本,但它不起作用:

#!/bin/sh$                                                                      
export PASSWORD= something                                                      
echo $PASSWORD | sudo -S su postgres                                                                                                                 
pg_dump somedb > dump.txt+`date +%Y-%m-%d`          

However when I run this script I do not get logged to postgres@gauss:$ at the same time script doesn't throw an error. 但是当我运行这个脚本时,我没有登录到postgres@gauss:$同时脚本不会抛出错误。 Is there something I am doing wrong here ? 我在这里做错了吗?

The reason your script fails is that the line 你的脚本失败的原因是该行

 echo $PASSWORD | sudo -S su postgres

causes su to fork a subordinate shell. 导致su分叉一个从属shell。 That shell tries to read from the standard input which has already been exhausted by sudo -S in reading the password. 该shell试图从读取密码的sudo -S已经耗尽的标准输入中读取。 When the shell finds no more input (EOF) it exits. 当shell找不到更多输入(EOF)时,它会退出。 The next line of your script then executes as if that quoted line never happened, and therefore runs under your UID. 然后执行脚本的下一行,就好像引用的行从未发生过一样,因此在您的UID下运行。

See j.hloetzek's answer for a much better way to do what you want. 请参阅j.hloetzek的答案,以便更好地完成您想要的操作。

Also the script as pasted has a two syntax errors in it, but you shouldn't use that approach anyway. 粘贴的脚本中也包含两个语法错误,但无论如何都不应该使用该方法。

您无法将密码传递给sudo命令,但可以在/etc/sudoers允许在没有密码的情况下运行某些命令(请检查确切的语法!)

username YOURUSERNAME = NOPASSWD: /sbin/su postgres

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

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