HTTP basic authentication using sockets in python

守給你的承諾、 提交于 2019-11-29 15:18:06

问题


How to connect to a server using basic http auth thru sockets in python .I don't want to use urllib/urllib2 etc as my program does some low level socket I/O operations


回答1:


Probably the easiest place to start is using makefile() to get a simpler file-like interface to the socket.

import socket, base64

host= 'www.example.com'
path= '/'
username= 'fred'
password= 'bloggs'
token= base64.encodestring('%s:%s' % (username, password)).strip()

lines= [
    'GET %s HTTP/1.1' % path,
    'Host: %s' % host,
    'Authorization: Basic %s' % token,
    'Connection: close',
]

s= socket.socket()
s.connect((host, 80))
f= s.makefile('rwb', bufsize=0)
f.write('\r\n'.join(lines)+'\r\n\r\n')
response= f.read()
f.close()
s.close()

You'll have to do a lot more work than that if you need to interpret the returned response to pick out the HTML or auth-required headers, and handle redirects, errors, transfer-encoding and all that right. HTTP can be complex! Are you sure you need to use a low-level socket?




回答2:


Look e.g. at urllib's sources, specifically the http_error_401 function (and the dispatching around it of course): make the HTTP request, watch for a 401 response, extract its realm, check that its scheme is basic, try again with the user and password for that realm (cfr function retry_http_basic_auth in that same source file). Lots of work of course, but that's the price of programming "down to the bare metal" as you require.



来源:https://stackoverflow.com/questions/2929532/http-basic-authentication-using-sockets-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!