Known Hosts Issue With Net::SSH

This issue bit me twice within a month, and each time I had to spend a couple of hours to figure out the cause of the problem, mostly due to the obscurity of the error messages.

So I was using net-ssh-2.0.15 and jruby-openssl-0.5.1 for a piece of code that’s supposed to perform some remote operations. The Net::SSH usage itself was straightforward…

Net::SSH.start(@host, @username, :keys => @keys) do |ssh|
    ...
end

When I ran the above snippet on Windows XP, it gave this error message without any further information…

The system cannot find the path specified

Not exactly helpful, eh? And after some sleuthing around, it came down to add(host, key) method in lib/net/ssh/known_hosts.rb :

def add(host, key)
  File.open(source, "a") do |file|
    blob = [Net::SSH::Buffer.from(:key, key).to_s].pack("m*").gsub(/s/, "")
    file.puts "#{host} #{key.ssh_type} #{blob}"
  end
end

This method is trying to add an entry to the known_hosts file, which location is stored in source variable. In my case, the variable resolved to C:/.ssh/known_hosts . But the problem was that the .ssh directory didn’t exist. So I simply created it.

Lo and behold, when I ran this piece of code on a Solaris box weeks later, I hit another error message…

No such file or directory (IOError)

which turned out to be caused by the exact same thing, but this time the location is /.ssh/known_hosts . The workaround was the same, I simply created the .ssh directory.

So there you go, hopefully it helps whoever else was confused by the unclear error messages. And in terms of a long term solution, it would be nice if add(host, key) checks or even creates the .ssh directory before attempting to write known_hosts file.

Share Comments
comments powered by Disqus