2014-10-01 37 views
1

我用發送密碼與使用子進程卡在一個死衚衕,我不知道什麼是錯的。我會很感激任何提示。Python:使用子進程發送postgres密碼

我的代碼:

os.system("sudo -u postgres -h " + db_host + " psql postgres -c \"\password\" ") 
os.system("sudo -u postgres -h " + db_host + " createuser " + db_user); 
print bcolors.WARNING, "Please enter your password for : " + db_user, bcolors.ENDC 
str = "sudo -u postgres -h " + db_host + " psql postgres -c \"\password " + db_user + "\"" 
# os.system(str) 
p = subprocess.Popen(['sudo','-u', 'postgres', '-h', db_host, 'psql', 'postgres', "-c", "\password", db_user],stdin=subprocess.PIPE, shell=False) 
p.communicate(raw_input("Please give me a password!") 

當使用os.system(str)一切都沒問題,但我希望可以捕捉到用戶輸入的密碼,並在未來,我想存儲在配置文件中的密碼。那可能嗎?

回答

2

停止正在做的事情,並使用psycopg2。請。你幾乎從不需要掏錢到psql。只需連接PostgreSQL的psycopg2本地客戶端驅動程序即可。

如果您需要連接一個超級用戶,修改pg_hba.conf允許從用戶md5密碼驗證,併爲postgres用戶的密碼。


os.system("sudo -u postgres -h " + db_host + " psql postgres -c \"\password\" ")

這是沒有意義的。您正試圖執行命令-h。你首先需要調用psql


sudo試圖避免從標準輸入讀取密碼。它關閉它的stdin並直接重新打開當前的tty作爲一種安全措施,以幫助阻止人們使用捕獲密碼的命令來包裝sudo

所以它的目的是打敗你想要做的。

您可以:

  • NOPASSWD模式sudopsql;
  • 使用sudo -ASUDO_ASKPASS環境變量中的askpass幫助器程序。您可以編寫一個SUDO_ASKPASS,通過爲您自己創建一個pipe()來從您的程序繼承的文件描述符中讀取密碼。
  • 使用sudo -n禁用密碼提示。如果需要密碼,sudo將失敗。
  • ...還是最重要的是,不使用sudo運行psql,只需使用psycopg2