0

How can I extract the hostname from: hostname:/file_name ? For example in ngs.pradhi.com:/upload, I want to extract ngs.pradhi.com from it and test it via ssh.connect.

How can I do that?

2 Answers 2

2

You should consider using the urlparse module:

This module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative URL” to an absolute URL given a “base URL.”

Example:

>>> import urlparse
>>> urlparse.urlparse('http://ngs.pradhi.com/upload')
ParseResult(scheme='http', netloc='ngs.pradhi.com', path='/upload', params='', query='', fragment='')
Sign up to request clarification or add additional context in comments.

1 Comment

In Python 3, this is now in the urllib.parse module, so either import urllib.parse and use with urllib.parse.urlparse(my_url) or import from urllib.parse import urlparse and use with urlparse(my_url)
1

The string in your example isn't a URL, so you won't be able to use the standard URL module (urlparse) to parse it. Here is how you can do it by hand:

In [43]: path = 'ngs.pradhi.com:/upload'

In [44]: path.split(':')[0]
Out[44]: 'ngs.pradhi.com'

For SSH, take a look at paramiko.

2 Comments

What if it is formed like http ://host:8080/etc/etc ?
@alemangui: There is no such requirement mentioned in the question. I suspect the use of the word "URL" is simply a misnomer. In any event, it would be helpful if the OP clarified this one way or the other.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.