如何在 ruby​​ 中处理 URL 以提取组成部分(方案、用户名、密码、主机等)?

发布于 2024-10-04 07:09:18 字数 434 浏览 6 评论 0原文

我正在尝试使用 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")

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

錯遇了你 2024-10-11 07:09:18

URIAddressable::URI 可以解析 URL 并让您将它们分解为各个组件。

URI 包含在 Ruby 的标准库中,这很好,但是 Addressable::URI 有更多功能,当我必须对 URL 进行大量工作时,我会使用它。

require 'addressable/uri'

uri = Addressable::URI.parse('ssh://user:[email protected]: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:[email protected]:81')
uri.host # => "www.example.com"
uri.user # => "user"
uri.password # => "pass"
uri.scheme # => "ssh"
uri.port # => 81

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:[email protected]: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:[email protected]:81')
uri.host # => "www.example.com"
uri.user # => "user"
uri.password # => "pass"
uri.scheme # => "ssh"
uri.port # => 81
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文