0

I am trying to replicate a wget command in a Python script. The wget command goes along these lines:

wget --user user --password pass http://serveraddress/

FYI, and as you can guess, it’s a simple authentication which is mandatory. You are prompted with a pop up form where you enter your username and password. So, unless you enter the credentials you can’t reach the address.
In my script, I prompt the user to enter his username and password and I store them. So far everything makes sense. However, after this I get really confused. The reason is that I read two different things on the web in general and in fact in Python Essential Reference about urllib2.urlopen() (FYI, I have to use the standard library only; so requests is not an option for me).
So, PER says “The basic urlopen() function does not provide support for authentication, cookies, or other advanced features of HTTP. To add support, you must create your own custom opener object using the build_opener() function.” Other people, for example here, say that you need to create a Request object and add headers to it. So, what am I missing here? Any help is much appreciate.

Community
  • 1
  • 1
Mahmoud
  • 231
  • 1
  • 4
  • 12

1 Answers1

2

Use the requests package. Your question is, in fact, the very first example they cite in their doc:

r = requests.get('https://api.github.com/user', auth=('user', 'pass'))

However, if you absolutely cannot use requests, the authors conveniently describe how to use the equivalent functionality in urllib2. Go to the requests documentation page, click on "See similar code, without Requests", and steal the urllib2 code from there.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • As I mentioned in the question, I have to use the standard library I am afraid. So, requests is not an option. :( – Mahmoud Aug 19 '15 at 19:35
  • In that case, go to the [`requests`](http://www.python-requests.org/en/latest/) documentation page, click on "See [similar code, without Requests](https://gist.github.com/973705)", and steal the `urllib2` code from there. – Robᵩ Aug 19 '15 at 19:38
  • Thanks. I am going to do so. – Mahmoud Aug 20 '15 at 10:45
  • @Robᵩ, is it possible to use a custom opener for the `auth` variable? I am trying to `HTTP PUT` documents to a sharepoint site and the `requests_ntlm` `HttpNtlmAuth` module is not working when given a `username` and `password` because of sharepoint's tokening system. Any hints would be much appreciated. – NickBraunagel Dec 02 '16 at 14:43
  • Sorry, @NickBraunagel, I don't know anything about NTLM or Sharepoint. If you haven't already, I suggest you reduce your program to a [mcve] and post it as a new question. – Robᵩ Dec 02 '16 at 16:53