Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Authentication with Python and urllib2

Tags:

python

urllib2

I want to grab some data off a webpage that requires my windows username and password.

So far, I've got:

opener = build_opener()
try:
    page = opener.open("http://somepagewhichneedsmywindowsusernameandpassword/")
    print page
except URLError:
    print "Oh noes."

Is this supported by urllib2? I've found Python NTLM, but that requires me to put my username and password in. Is there any way to just grab the authentication information somehow (e.g. like IE does, or Firefox, if I changed the network.automatic-ntlm-auth.trusted-uris settings).

Edit after msander's answer

So I've now got this:

# Send a simple "message" over a socket - send the number of bytes first,
# then the string.  Ditto for receive.
def _send_msg(s, m):
    s.send(struct.pack("i", len(m)))
    s.send(m)

def _get_msg(s):
    size_data = s.recv(struct.calcsize("i"))
    if not size_data:
        return None
    cb = struct.unpack("i", size_data)[0]
    return s.recv(cb)

def sspi_client():
    c = httplib.HTTPConnection("myserver")
    c.connect()
    # Do the auth dance.
    ca = sspi.ClientAuth("NTLM", win32api.GetUserName())
    data = None
    while 1:
        err, out_buf = ca.authorize(data) # error 400 triggered by this line
        _send_msg(c.sock, out_buf[0].Buffer)

        if err==0:
            break

        data = _get_msg(c.sock)

    print "Auth dance complete - sending a few encryted messages"
    # Assume out data is sensitive - encrypt the message.
    for data in "Hello from the client".split():
        blob, key = ca.encrypt(data)
        _send_msg(c.sock, blob)
        _send_msg(c.sock, key)
    c.sock.close()
    print "Client completed."

which is pretty well ripped from socket_server.py (see here). But I get an error 400 - bad request. Does anyone have any further ideas?

Thanks,

Dom

like image 939
Dominic Rodger Avatar asked May 26 '09 08:05

Dominic Rodger


1 Answers

Assuming you are writing your client code on Windows and need seamless NTLM authentication then you should read Mark Hammond's Hooking in NTLM post from the python-win32 mailing list which essentially answers the same question. This points at the sspi example code included with the Python Win32 extensions (which are included with ActivePython and otherwise can be downloaded here).

like image 88
msanders Avatar answered Oct 16 '22 08:10

msanders