Ruby net/ftp code failing to PUT a file because of

2019-08-09 17:28发布

问题:

I have this basic code that is failing:

  ftpconfighash = open("#{RAILS_ROOT}/config/ftp.yml") {|f| YAML.load(f) }
  config = ftpconfighash[12345]

  ftp = Net::FTP::new(config["host"])
  ftp.login(config["username"], config["password"])

  dir += "/" unless config["dir"].blank? or config["dir"].ends_with?("/")
  remotename = File.basename(filename)
  remotename = dir + remotename unless dir.blank?

  if File.binary?(filename)
    puts "PUTting binary file #{filename} to #{remotename}"
    ftp.putbinaryfile(filename, remotename)
  else
    puts "PUTting ASCII file #{filename} to #{remotename}"
    ftp.puttextfile(filename, remotename)
  end
  ftp.close

I have verified that I can ftp to the server and PUT a file by hand. I have also used irb to walk through the code line-by-line. I am using an XML file as a test, so the "ftp.puttextfile" is the line that is failing. Here is the error:

Net::FTPPermError: 500 Invalid PORT Command.

I don't understand. I have verified that I can indeed put this file, but I just can't do it with this code.

I set ftp.debug_mode to true, and this is the output from the ftp.puttextfile command:

put: TYPE A
get: 200 Type set to A.
put: PORT 10,0,1,20,198,170
get: 500 Invalid PORT Command.
Net::FTPPermError: 500 Invalid PORT Command.

from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/ftp.rb:243:in `getresp'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/ftp.rb:251:in `voidresp'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/ftp.rb:274:in `voidcmd'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/monitor.rb:242:in `synchronize'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/ftp.rb:272:in `voidcmd'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/ftp.rb:287:in `sendport'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/ftp.rb:295:in `makeport'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/ftp.rb:328:in `transfercmd'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/ftp.rb:424:in `retrlines'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/monitor.rb:242:in `synchronize'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/ftp.rb:422:in `retrlines'
from /Users/me/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/ftp.rb:631:in `list'
from (irb):42

It looks like Ruby is trying to run a command that the FTP server doesn't understand:

PORT 10,0,1,20,198,170

Is there some way to suppress that command, or am I missing something else?

回答1:

Try using passive ftp:

ftp = Net::FTP::new(config["host"])
ftp.login(config["username"], config["password"])

ftp.passive = true


标签: ruby ftp