Ruby - Expect和Pty的问题

时间:2023-01-05 21:01:01

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:

我正在尝试编写一个Ruby脚本,它将ssh到服务器,运行给定的命令,并从中获取输出。这是我到目前为止所做的,主要是改编自Ruby编程的书:

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?

知道我做错了什么以及如何缓解这个问题?

2 个解决方案

#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

为此,我建议使用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.

查看http://www.42klines.com/2010/08/14/what-to-expect-from-the-ruby-expect-library.html - 它有一些很好的例子,使用PTY有和没有Ruby的期望。

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

我经常发现只使用PTY更容易,因为我可以查看我的“缓冲区”并找出正在发生的事情。

#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

为此,我建议使用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.

查看http://www.42klines.com/2010/08/14/what-to-expect-from-the-ruby-expect-library.html - 它有一些很好的例子,使用PTY有和没有Ruby的期望。

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

我经常发现只使用PTY更容易,因为我可以查看我的“缓冲区”并找出正在发生的事情。