There is another easier way to drive shell commands from ruby and capture sdout, sterr and send stdin. My favorite is a gem called session:
$ sudo gem install session
Then its really easy to drive a shell in a subprocess. here's an example that will make a bash shell in ruby with prompts and everything:
Code:
#!/usr/bin/env ruby
require 'tempfile'
require 'readline'
include Readline
require 'rubygems'
require 'session'
shell = Session::Shell.new
require 'tempfile'
require 'readline'
include Readline
n = 0
loop do
command = readline("#{ n }: SHELL > ", true)
if command =~ /^\s*\!*history\!*\s*$/
open('shell.history','w'){|f| f.puts shell.history}
next
end
exit if command =~ /^\s*(?:exit|quit)\s*$/io
out, err = shell.execute command
out ||= ''
err ||= ''
printf "STDOUT:\n%s\nSTDERR:\n%s\n", out.gsub(%r/^/,"\t"), err.gsub(%r/^/,"\t")
n += 1
end
Here is a little simpler example of just sending an ls command and capturing stout and sterr:
Code:
require 'tempfile'
require 'rubygems'
require 'session'
shell = Session::Shell.new :history => false
shell.execute('ls -ltar') do |out, err|
if out
puts "OUT:\n#{ out }"
elsif err
puts "ERR:\n#{ err }"
end
end
puts shell.history
Hopefully that help some. But Net::SSH is a great tool to drive ssh commands. And Net::SFTP might be worth l;ooking at too if you are trying to copy files from a remote server securely.
Cheers
-Ezra
Bookmarks