我正在尝试创建一个脚本,以便使用Ruby从FTP服务器列出和下载数据。我是Ruby的新手,所以我查找了如何使用Net :: FTP的文档。我无法理解为什么这不起作用:
require 'net/ftp'
server = "ftp.server.com"
user = "myuser"
password = "mypassword"
Net::FTP.open(server, user, password) do |ftp|
files = ftp.chdir('mydirectory/')
files = ftp.list
puts "list out of directory:"
puts files
end
这不起作用,返回此错误:
/home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/ftp.rb:298:in `getresp': 425 >Failed to establish connection. (Net::FTPTempError) from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/ftp.rb:325:in `block in sendcmd' from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize' from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/ftp.rb:323:in `sendcmd' from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/ftp.rb:402:in `transfercmd' from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/ftp.rb:478:in `block (2 levels) in retrlines' from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/ftp.rb:178:in `with_binary' from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/ftp.rb:477:in `block in retrlines' from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize' from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/ftp.rb:476:in `retrlines' from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/ftp.rb:722:in `list' from test_ftp.rb:10:in `block in ' from /home/adhown/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/net/ftp.rb:116:in `open' from test_ftp.rb:8:in `'
有人能解释我的剧本有什么问题吗?
答案 0 :(得分:39)
您的代码适用于我。我怀疑问题可能是因为Net::FTP
连接模式,默认情况下是活动的。尝试使用被动模式进行连接,遵循代码示例 -
ftp = Net::FTP.new(server)
ftp.passive = true
ftp.login user, password
files = ftp.chdir('mydirectory/')
files = ftp.list
puts "list out of directory:"
puts files
ftp.close
如果你很好奇,以下是主动和被动模式之间的difference(来自维基百科)。
答案 1 :(得分:2)
以下脚本可以在我的机器上运行,并且基于您的机器,并进行小规模清理:
require 'net/ftp'
Net::FTP.open('ftp.linuxjournal.com', 'anonymous', 'anonymous@google.com') do |ftp|
ftp.chdir('pub/')
files = ftp.list
puts "list out of directory:"
puts files
end
这是我得到的输出:
list out of directory:
lrwxrwxrwx 1 root ftp 32 Jul 12 2010 00-README-TO-UPLOAD-FILES.txt -> ../00-README-TO-UPLOAD-FILES.txt
drwxr-sr-x 3 root ftp 21 Mar 7 2001 elj
drwxr-sr-x 3 root ftp 4096 Jan 6 2004 lg
drwxr-sr-x 8 root ftp 113 Jun 21 2010 lj
drwxr-sr-x 5 root users 112 Oct 2 2007 ssc
drwxr-sr-x 2 root ftp 4096 Jan 3 17:21 tux
我说代码有效,问题出在其他地方。
由于425 >Failed to establish connection
我认为您应该检查您的DNS和/或防火墙。