如何处理Ruby中的URL来提取组件零件(方案,用户名,密码,主机等)?
题
我正在尝试使用Ruby(和NET :: SSH)创建一个程序,以连接到服务器并执行一些任务。服务器的详细信息应以类似的方式提供:
ssh://user:pass@host:port (for a host that does not yet have SSH keys)
或者
user@host
NET :: SSH期望以下格式:
Net::SSH.start('host', 'user', :password => "password")
是否有可以将URL处理为此格式的GEM/STDLIB?还是可以匹配不同零件的简单正则义务?
注意:我知道并使用Capistrano,但是在这种情况下,我需要较低级别的控制。
解决方案
两个都 Uri 和 可寻址:: Uri 可以解析URL,让您将它们分解为它们的组件。
URI包含在Ruby的标准库中,这很好,但是可寻址:: URI具有更多功能,并且是我必须在URL上进行大量工作时使用的功能。
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
其他提示
有一个 Uri 应该有帮助的课程。您可能必须替换 ssh
方案与 http
首先,我不认为 URI
了解 ssh
计划开箱即用。
不隶属于 StackOverflow