我在使用子流程发送密码方面陷入了死胡同,我不知道出了什么问题。如果有任何提示,我将不胜感激。
我的代码:
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)
时,一切都可以,但我想从用户那里获取键入的密码,将来我想将密码存储在配置文件中。这可能吗?
停止您正在做的事情,并使用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读取密码。它关闭其stdin并直接重新打开当前tty,作为一种安全措施,以帮助阻止人们用陷阱密码的命令包装sudo
。
所以它的设计是为了击败你试图做的事情
您可以:
psql
在sudo
中设置NOPASSWD
模式- 将
sudo -A
与SUDO_ASKPASS
环境变量中的askpass助手程序一起使用。您可以编写一个SUDO_ASKPASS
,通过为自己创建pipe()
,从程序继承的文件描述符中读取密码 - 使用
sudo -n
禁用密码提示。如果需要密码,sudo
将失败 - 。。。或者最好的是,不要使用
sudo
来运行psql
,只使用psycopg2