如何处理ruby中的URL以提取组成部分(方案,用户名,密码,主机等)? [英] How do I process a URL in ruby to extract the component parts (scheme, username, password, host, etc)?

查看:236
本文介绍了如何处理ruby中的URL以提取组成部分(方案,用户名,密码,主机等)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ruby(和Net :: SSH)创建一个程序以连接到服务器并执行一些任务.服务器的详细信息将以类似以下方式提供:

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)

user@host

Net :: SSH需要以下格式:

Net::SSH expects the following format:

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

是否有gem/stdlib可以将URL处理为这种格式?还是可以匹配不同部分的简单正则表达式?

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

注意:我知道并使用capistrano,但在这种情况下,我需要较低级别的控制.

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

推荐答案

两者 URI Addressable :: URI 可以解析URL,并让您将其分解为它们的组成部分.

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

URI包含在Ruby的标准库中,这很好,但是Addressable :: URI具有更多功能,这是我在URL上要做很多工作时要使用的.

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

这篇关于如何处理ruby中的URL以提取组成部分(方案,用户名,密码,主机等)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆