10

I need to run a command on the command-line that asks for a user response. In case it helps the command is:

gpg --recipient "Some Name" --encrypt ~/some_file.txt

when you run this, it warns about something then asks:

Use this key anyway? (y/N)

Responding 'y' let's it finish correctly. I have been trying to use the open4 gem but I have not been able to get it to specify the 'y' correctly. Here is what I tried:

Open4::popen4(cmd) do |pid, stdin, stdout, stderr|
  stdin.puts "y"
  stdin.close

  puts "pid        : #{ pid }"
  puts "stdout     : #{ stdout.read.strip }"
  puts "stderr     : #{ stderr.read.strip }"
end

What am I doing wrong? Is what I am doing even possible?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
chrishomer
  • 4,900
  • 5
  • 38
  • 52
  • The blunt option is to do `yes | gpg --recipient "Some Name" --encrypt ~/some_file.txt`, but that will answer "y" to everything. – Andrew Marshall May 18 '12 at 01:19

2 Answers2

11

The Unix way to handle these situations is with expect, which Ruby comes with built-in support for:

require 'pty'
require 'expect'

PTY.spawn("your command here") do |reader, writer|
  reader.expect(/Use this key anyway/, 5) # cont. in 5s if input doesn't match
  writer.puts('y')
  puts "cmd response: #{reader.gets}"
end
Abe Voelker
  • 30,124
  • 14
  • 81
  • 98
  • Tried this and it's perfect. Thanks. – chrishomer May 18 '12 at 01:11
  • No problem... ideally `writer.puts('y')` would be in a block that gets passed to `reader.expect`, and only get evaluated if the input matches, but that's not really the way the library works. Might want to tinker with that a bit... – Abe Voelker May 18 '12 at 01:16
4

gpg is probably opening the terminal device directly to ask the user the question -- this is a common safety approach to prevent driving a script entirely from files. (See the now-deprecated getpass(3) routine for something similar.)

If you don't actually care enough about the warning to read it, you might as well use the gpg command line option --yes:

   --yes  Assume "yes" on most questions.
sarnold
  • 102,305
  • 22
  • 181
  • 238
  • I don't have --yes as an option in my gpg command. Both Mac and Ubuntu. – chrishomer May 18 '12 at 00:33
  • Really? How old is your Ubuntu? Even the [hardy version](http://packages.ubuntu.com/hardy/gnupg) has `--yes` documented as an option... – sarnold May 18 '12 at 00:36
  • Ok looks like it exists at the OS level but it does not cause the question to be answered as "yes". It still prompts for it. Same on Mac. (ubuntu 9.10) – chrishomer May 18 '12 at 00:42