Ruby - Problems with Expect and Pty

Ruby - Problems with Expect and Pty

For this I recommend using the net-ssh gem: sudo gem install net-ssh: http://net-ssh.rubyforge.org/ssh/v2/api/index.html

The code goes a little like this:

require 'rubygems'
require 'net/ssh'

Net::SSH.start('your-server', 'username', :password => "password") do |ssh|
puts ssh.exec!("ls -la")
end

How to determine when PTY.spawn has finished in ruby script so then to start new process

To help you debug, I reduced the code a bit, and spawned a more benign command:

require 'pty'
require 'expect'

PTY.spawn("sleep 1;echo 1") do |reader, writer, pid|
puts reader.expect(/1/)
Process.wait(pid)
end

PTY.spawn("sleep 1;echo 2") do |reader, writer, pid|
puts reader.expect(/2/)
Process.wait(pid)
end

This outputs:

ruby test.rb 
1
2

This implies to me that the problem lies in the apt-get commands.

Non greedy regular expressions in Ruby: pty and expect

Looks like the carriage return is confusing the "+" quantifier.

The below matches the entire line, including the carriage return (which messes up the output formatting and should be trimmed)

   reader.expect(/Thank you! Your password is: \w+\r/) do |output|

Good luck.

Run `git add -p` from ruby

Inside the pty standard library module (no gems needed here) is an inner module you can require called expect. It will add an expect method to IO.

You probably want something like this:

require 'pty'
require 'expect'

PTY.spawn "git add -p" do |r, w, pid|
w.sync = true
r.expect ']? ' do |got|
puts got
puts 'responding with q'
w.write "q\r"
puts r.expect "\n", 9
end
end

Ruby on Linux PTY goes away without EOF, raises Errno::EIO

So I had to go as far as reading the C source for the PTY library to get really satisfied with what is going on here.

The Ruby PTY doc doesn't really say what the comments in the source code say.

My solution was to put together a wrapper method and to call that from my script where needed. I've also boxed into the method waiting on the process to for sure exit and the accessing of the exit status from $?:

# file: lib/safe_pty.rb

require 'pty'
module SafePty
def self.spawn command, &block

PTY.spawn(command) do |r,w,p|
begin
yield r,w,p
rescue Errno::EIO
ensure
Process.wait p
end
end

$?.exitstatus
end
end

This is used basically the same as PTY.spawn:

require 'safe_pty'
exit_status = SafePty.spawn(command) do |r,w,pid|
until r.eof? do
logger.debug r.readline
end
end

#test exit_status for zeroness

I was more than a little frustrated to find out that this is a valid response, as it was completely undocumented on ruby-doc.

Ruby Net::SSH get Exit Status in PTY

You may want to take a look at the source for the Ruby "ssh" gem and "remote_task" gem.

  • http://rubygems.org/gems/ssh

The relevant source code is here:

  • https://github.com/seattlerb/ssh/blob/master/lib/ssh.rb

It has code for handling the "cd" command, i/o channels, and the exit status.



Related Topics



Leave a reply



Submit