3

I'm trying create a program using ruby (and Net::SSH) to connect to servers and perform some tasks. The details of the server are to be provided as something like:

ssh://user:pass@host:port (for a host that does not yet have SSH keys)

or

user@host

Net::SSH expects the following format:

Net::SSH.start('host', 'user', :password => "password")

Is there are gem/stdlib that can process the URL into this format? Or a simple regex that can match the different parts?

Note: I'm aware of, and use, capistrano but in this case I need lower level control.

Luke Chadwick
  • 1,648
  • 14
  • 24

1 Answers1

14

Both URI and Addressable::URI can parse URLs and let you break them down into their components.

URI is included in Ruby's Standard Library, which is nice, but Addressable::URI has more features, and is what I use when I have to do a lot of work on URLs.

require 'addressable/uri'

uri = Addressable::URI.parse('ssh://user:pass@www.example.com:81') 
uri.host # => "www.example.com"
uri.user # => "user"
uri.password # => "pass"
uri.scheme # => "ssh"
uri.port # => 81

require 'uri'
uri = URI.parse('ssh://user:pass@www.example.com:81')
uri.host # => "www.example.com"
uri.user # => "user"
uri.password # => "pass"
uri.scheme # => "ssh"
uri.port # => 81
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • URI does not, apparently, work when given just 'user@host' though. Which explains how I managed to try it yesterday before I asked the question and thought that it didn't extract the components. (After testing - neither does addressable/uri) – Luke Chadwick Nov 25 '10 at 22:09
  • 1
    'user@host' isn't enough info for the parsers to do anything useful. It could be interpreted as an email address fragment, or the user at a host fragment. Because it's ambiguous I'd want the parsers to bail. YOU could sense and parse that easily enough and supply the missing scheme ("ssh:"), but that's because you have special knowledge of the problem that the parsers don't have. – the Tin Man Nov 26 '10 at 00:17
  • True, I was thinking that this morning. – Luke Chadwick Nov 26 '10 at 02:18
  • All in all, tearing up URLs is usually not that difficult and we can get away with simple regex but when we get into dealing with arbitrary URLs or uncontrolled query lists that we get into trouble, the regex patterns meltdown, and the app dies. The parsers shine then. – the Tin Man Nov 26 '10 at 02:23