Ruby - Problems with Expect and Pty

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

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 root@x.y") do |reader, writer, pid|   reader.expect(/root@x.y'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?

回答1:

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 


回答2:

Check out http://www.42klines.com/2010/08/14/what-to-expect-from-the-ruby-expect-library.html - it has some nice examples of using PTY with and without Ruby's expect.

I often find it easier to only use PTY, as I can look at my "buffer" and work out what's happening.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!