我想从需要我的Windows用户名和密码的网页上获取一些数据。
到目前为止,我已经:
opener = build_opener()
try:
page = opener.open("http://somepagewhichneedsmywindowsusernameandpassword/")
print page
except URLError:
print "Oh noes."
urllib2是否支持此功能?我找到了Python NTLM,但这需要我输入我的用户名和密码。有没有办法只是以某种方式获取身份验证信息(例如,像IE一样,或Firefox,如果我更改了{{1}设置)。
所以我现在得到了这个:
network.automatic-ntlm-auth.trusted-uris
这很好地从# 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."
撕掉了(见here)。但我得到一个错误400 - 错误的请求。有没有人有任何进一步的想法?
谢谢,
的Dom
答案 0 :(得分:16)
假设您正在Windows上编写客户端代码并需要无缝的NTLM身份验证,那么您应该阅读来自python-win32邮件列表的Mark Hammond的Hooking in NTLM帖子,它基本上回答了同样的问题。这指向Python Win32扩展中包含的sspi示例代码(包含在ActivePython中,否则可以是downloaded here)。
答案 1 :(得分:-2)
网站可以使用多种形式的身份验证。
HTTP身份验证。这是浏览器弹出一个窗口,供您输入用户名和密码。有两种机制:基本和摘要。有一个“授权”标题随页面一起告诉浏览器(或使用urllib2的程序)该怎么做。
在这种情况下,您必须配置urlopener以提供授权标头需要查看的答案。您需要构建HTTPBasicAuthHandler或HTTPDigestAuthHandler。
AuthHandlers需要PasswordManager。这个密码管理器可能有一个硬编码的用户名和密码(很常见),或者它可能很聪明,可以从某些Windows API中找出你的Windows密码。
应用程序身份验证。这是Web应用程序将您引导到包含您使用用户名和密码填写的表单的页面。在这种情况下,您的Python程序必须使用urllib2来执行POST(request with data),其中数据是正确填写的表单。对帖子的回复通常包含一个cookie,允许您进一步访问。你不需要担心cookie,urllib2会自动处理这个问题。
你怎么知道你有哪些?您可以在响应中转储标头。来自urllib2.openurl的回复包括所有标题(在page.info()
中)以及页面内容。
阅读HTTP Authentication in Python
How do you access an authenticated Google App Engine service from a (non-web) python client?