Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Problems with Expect and Pty

Tags:

ruby

pty

expect

I'm trying to write a Ruby script that will ssh over to a server, run a given command, and fetch the output from it. Here's what I've got so far, mostly adapted from the Programming Ruby book:

require 'pty'
require 'expect'

$expect_verbose = true
PTY.spawn("ssh [email protected]") do |reader, writer, pid|
  reader.expect(/[email protected]'s password:.*/)
  writer.puts("password")
  reader.expect(/.*/)
  writer.puts("ls -l")
  reader.expect(/.*/)
  answer = reader.gets
  puts "Answer = #{answer}"
end

Unfortunately all I'm getting back is this:

Answer = .y's password:

Any idea what I've done wrong and how to alleviate this?

like image 657
Chris Bunch Avatar asked Jan 23 '23 21:01

Chris Bunch


1 Answers

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
like image 183
Ryan Bigg Avatar answered Jan 26 '23 09:01

Ryan Bigg