Sftp.put_file problems on Linux

I have written a simple script to locate particular files on a server
and copy them elsewhere with sftp. There is one particular part of the
script that gives me some trouble:

begin
  sftp.put_file("#{ramdisk}/#{file}","#{dst_dir}")
rescue
  puts "Message: #{sftp.status[:code]} (#{sftp.status[:message]})"
end

The code dies at this point, with this error.

Message: 0 (Success)
/var/lib/gems/1.8/gems/net-sftp-1.1.1/lib/net/sftp/operations/abstract.rb:78:in
`do_status': Net::SFTP::Operations::StatusException (4, "Failure")
(Net::SFTP::Operations::StatusException (4, "Failure"))
        from
/var/lib/gems/1.8/gems/net-sftp-1.1.1/lib/net/sftp/session.rb:221:in
`do_status'
        from /usr/lib/ruby/1.8/rubygems/custom_require.rb:27:in
`to_proc'
        from
/var/lib/gems/1.8/gems/net-sftp-1.1.1/lib/net/sftp/protocol/01/impl.rb:92:in
`call'
        from
/var/lib/gems/1.8/gems/net-sftp-1.1.1/lib/net/sftp/protocol/01/impl.rb:92:in
`call_on_status'
        from
/var/lib/gems/1.8/gems/net-sftp-1.1.1/lib/net/sftp/protocol/03/impl.rb:37:in
`do_status'
        from
/var/lib/gems/1.8/gems/net-sftp-1.1.1/lib/net/sftp/protocol/01/impl.rb:189:in
`dispatch'
        from
/var/lib/gems/1.8/gems/net-sftp-1.1.1/lib/net/sftp/protocol/driver.rb:189:in
`do_data'
        from /usr/lib/ruby/1.8/rubygems/custom_require.rb:27:in
`to_proc'
         ... 20 levels...
        from
/var/lib/gems/1.8/gems/net-ssh-1.1.2/lib/net/ssh/session.rb:138:in
`initialize'
        from /var/lib/gems/1.8/gems/net-ssh-1.1.2/lib/net/ssh.rb:47:in
`new'
        from /var/lib/gems/1.8/gems/net-ssh-1.1.2/lib/net/ssh.rb:47:in
`start'
        from ./sftp_script.rb:26

Everything else is fine - the connection is set up properly and I can
use sftp.mkdir. Also, if I replace put_file with this, it works:

scp_command = "scp #{ramdisk}/#{file}
#{user}@#{host}:/home/#{user}/#{dst_dir}"
unless system("#{scp_command}")
  raise "Could not scp #{file}."
end

This is less than ideal due to filling up the logs of the receiving
machine, though.
Does anyone know what might be causing the problem with put_file?

Seems to me like your TCP connection is being killed by the server.
I’m guessing.

Try adding a keep-alive to your /etc/ssh/ssh_config

ServerAliveInterval 15

unlike sftp, scp will open a new connection for each file.

Michael S. wrote:

Seems to me like your TCP connection is being killed by the server.
I’m guessing.

Thanks for your reply.
I’m not sure that that’s it, as my script includes other commands (e.g.
sftp.mkdir) that work fine even though all the put_file commands fail.
So, the connection must be remaining open. I can also use sftp on the
command line.
Could there be some sort of status message being returned from the ssh
connection that the Ruby code doesn’t like?