Using Ruby popen and PostgreSQL createuser
I am attempting to write a very simple rake task (and merge it into a rather large rake task) that will call the following command and pass in a randomly generated password. For the moment, let's even fake the random generation and just give it a set password of 'test':
createuser -SDPRE test
The code I have f开发者_Go百科or my task is as follows:
desc "Create a test user with test password"
task "test" do
puts('Creating User')
IO.popen "createuser -SDRPE test", 'w+' do |io|
io.write "test\ntest\n"
io.close_write
end
raise 'createuser failed' unless $?.success?
end
The io.write
appears not to work as I still have to enter the password. It's also not being clobbered. After running the task and entering the password manually, I can use that password to log in with psql
.
I have tried quite a few variations such as io.close
, opening the file as 'w'
and even 'r'
or 'r+'
because I saw other examples that use it.
I am a bit stumped on how to get this to work. Any ideas/comments/answers would be greatly appreciated!
Edit 1: This is on a Debian (Lenny) Linux system in case it makes any difference.
createuser
is opening /dev/tty
to read the password
Programs that read passwords usually sacrifice the Unix tools paradigm with respect to passwords. This is a reasonable thing to do because it allows other functionality to respect standard input and output, and put it all on pause while it opens /dev/tty
for an interactive password.
In any case, an strace(1)
reveals that createuser
is in fact opening /dev/tty
.
All is not lost, createuser
is just a link to /usr/share/postgresql-common/pg_wrapper
which is a Perl program. I'm sure it can be hacked for password scripting compatibility.
I know this is not an answer to your question, but have you considered creating PG user by using SQL instead of invoking shell commands?
http://www.postgresql.org/docs/8.0/interactive/sql-createuser.html
It seems safer and more reliable.
精彩评论