# A solution for public-keyed SFTP and Ruby

**URL:** <https://www.ruby-forum.com/t/a-solution-for-public-keyed-sftp-and-ruby/68670>\
**Category:** Ruby\
**Created:** [September 14, 2006, 10:08am UTC](https://www.ruby-forum.com/t/a-solution-for-public-keyed-sftp-and-ruby/68670 "2006-09-14T10:08:25Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Pau\_Garcia\_i\_Quiles](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/b9e5f3/32.png) [@Pau\_Garcia\_i\_Quiles](https://www.ruby-forum.com/u/Pau_Garcia_i_Quiles)\
**Post date:** [September 14, 2006, 10:08am UTC](https://www.ruby-forum.com/t/a-solution-for-public-keyed-sftp-and-ruby/68670/1 "2006-09-14T10:08:25Z")

</div>

Hello,

Lately there has been some talking here on how to send files using scp.  
Some  
people are doing just fine by calling scp with a pre-shared password,  
but  
neither I like that approach nor does it work for my purpose, so I did a  
bit  
of experimentation and found this code works:

=========  
require ‘net/ssh’  
require ‘net/sftp’

class SSHAgent  
def initialize  
@agent\_env = Hash.new  
agenthandle = IO.popen(“/usr/bin/ssh-agent -s”, “r”)  
agenthandle.each\_line do |line|  
if line.index(“echo”) == nil  
line = line.slice(0…(line.index(‘;’)-1))  
key, value = line.chomp.split(/=/)  
puts “Key = #{key}, Value = #{value}”  
@agent\_env[key] = value  
end  
end  
end  
def   
return @agent\_env[key]  
end  
end

agent = SSHAgent.new  
ENV[“SSH\_AUTH\_SOCK”] = agent[“SSH\_AUTH\_SOCK”]  
ENV[“SSH\_AGENT\_PID”] = agent[“SSH\_AGENT\_PID”]  
system(“/usr/bin/ssh-add”)

Net::SSH.start( ‘192.168.1.12’,  
:username=\>‘pgquiles’,  
:compression\_level=\>0,  
:compression=\>‘none’  
) do |session|

```
    session.sftp.connect do |sftp|
            sftp.put_file("bigvideo.avi", "bigvideo.avi")
    end

```

# end

I was using a passwordless private key for this experiment. Should you  
want to  
use a password-protected private key, you might want to set the DISPLAY  
and  
SSH\_ASKPASS environment variables or use a smartcard reader and the ‘-s  
reader’ parameter.

The SSHAgent class comes from [Paste number 6912: Ruby version](http://paste.lisp.org/display/6912) (I  
don’t know  
who its author is or the license that code is released under)

Lastly, there is an undesired behaviour in Net::SFTP: when you use the  
put\_file method it loads the whole file in memory, therefore you need  
loads  
of memory if you want to send big files. I’ve tried a naive fix  
(iterating  
writes) but it didn’t work (it complains about “no such file”, I think  
it’s a  
channels-related issue). Jamis B., the author of Net::SFTP, told me  
currently he has no time to fix this issue. In case you feel brave  
enough,  
the offending method starts in line 202 in  
net-sftp-1.1.0/lib/net/sftp/session.rb
