2017-05-05 53 views
0

我有一個Ubuntu服務器處理文件和另一個有數據庫(postgresql 9.3)。運行postgres查詢從另一臺服務器,在bash

我跑psql -?瞭解如何連接到另一個數據庫,並最終命令是:

psql -U postgres -W -h 1.2.3.4 -d testdb -p 5432 

它的工作原理,但發出的命令後,我必須輸入密碼。

我是想在bash腳本來適應這個命令:

#!/bin/bash 
psql -U postgres -W mypassword -h 1.2.3.4 -d testdb -p 5432 << EOF 
select * from mytable; 
\q 
EOF 

不用說,這是不正確的命令。 此外,密碼不會被識別爲一個密碼,報告錯誤:

psql: warning: extra command-line argument "mypassword" ignored 
Password for user postgres: 
psql: FATAL: password authentication failed for user "postgres" 
FATAL: password authentication failed for user "postgres" 

在另一臺服務器,在腳本上的本地數據庫運行時,我的工作腳本是:

su - postgres -c "psql myDatabase" << EOF 
select * from "myOtherTable"; 
\q 
EOF 

的問題很簡單,我怎樣才能爲bash編寫正確的命令,用用戶/密碼連接到另一個數據庫併發出命令?

的鏈接我試過了,但密碼好像不能設置: run psql query in bash

謝謝!

回答

1

嘗試

PGPASSWORD=yourpass psql -U postgres -W -h 1.2.3.4 -d testdb -p 5432 

參見:https://www.postgresql.org/docs/9.3/static/libpq-envars.html

或〜/ .pgpass文件https://www.postgresql.org/docs/9.3/static/libpq-pgpass.html

+0

良好的聯繫!謝謝我檢查出來,工作時會標記你的答案(: – Nihvel

+0

)起初它一直在詢問密碼,然後它就停止了,測試服務器重新啓動,腳本運行並且工作! 我試過了.pgpass解決方案。在根文件夾中,對0600的權限和腳本中的命令是'psql -U postgres -h 1.2.3.4 -d dbname << eof [...] \ q eof' – Nihvel

相關問題