Ruby - Expect 和 Pty 的问题
我正在尝试编写一个 Ruby 脚本,它将通过 ssh 连接到服务器,运行给定的命令,并从中获取输出。 这是我到目前为止所得到的内容,大部分改编自 Programming Ruby 一书:
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
不幸的是,我得到的只是这样:
Answer = .y's password:
知道我做错了什么以及如何缓解这个问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为此,我建议使用 net-ssh gem:
sudo gem install net-ssh
: http://net-ssh.rubyforge.org/ssh/v2/api/index.html代码有点像这样:
For this I recommend using the net-ssh gem:
sudo gem install net-ssh
: http://net-ssh.rubyforge.org/ssh/v2/api/index.htmlThe code goes a little like this:
查看 http:// /www.42klines.com/2010/08/14/what-to-expect-from-the-ruby-expect-library.html - 它有一些使用 PTY 的很好的例子,有或没有 Ruby 的期望。
我经常发现只使用 PTY 更容易,因为我可以查看我的“缓冲区”并弄清楚发生了什么。
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.