Search code examples
pythonurllib2ntlm

Python NTLM login


I am trying to pull information from a url that requires NTLM login.

I originaly received 401 error and after some tweaks have been able to pull the page stating that I have input invalid credentials.

The username and password are correct yet I cannot get past the invalid credentials page.

Lgn2.py:

import urllib2
import HTTPNtlmAuthHandler

login = open('c:/temp/login.txt')
open = login.read()
to = open.split()
user = str(to[0])
password = str(to[1])

url = "http://INSERT URL HERE.com/"
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, password)
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)


opener = urllib2.build_opener(auth_NTLM)
urllib2.install_opener(opener)


response = urllib2.urlopen(url)
print(response.read())

I have a username including a \ using the method above I do not get a double backslash in the name when it prints. Should I keep it to where print will have the double backslash in the name as apposed to exactly as the txt file has the username spelled?

The txt file is just a txt document with only: domain\user\name password.

The second backslash in the middle of username would be part of the username.

Any help would be appreciated.


Solution

  • Maybe you didn't use a raw string:

    Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C.

    >>> 'domain\user'
      File "<stdin>", line 1
    SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 6-7: truncated \uXXXX escape
    >>> r'domain\user'
    'domain\\user'
    

    This works for me (in Python 2, not 3):

    from ntlm import HTTPNtlmAuthHandler
    import urllib2
    
    user = r'domain\user'
    password = "passphrase"
    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passman.add_password(None, "http://projects/", user, password)
    auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
    opener = urllib2.build_opener(auth_NTLM)
    urllib2.install_opener(opener)
    
    url = "http://projects/_vti_bin/owssvr.dll?Cmd=Display&List=etc"
    response = urllib2.urlopen(url)
    headers = response.info()
    print("headers: {}".format(headers))
    body = response.read()
    print("response: " + body)