Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run system command in ruby and interact with it

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?

like image 430
chrishomer Avatar asked May 18 '12 00:05

chrishomer


1 Answers

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
like image 86
Abe Voelker Avatar answered Sep 25 '22 17:09

Abe Voelker