python-ntlm认证

转自:http://www.cnblogs.com/yd1227/archive/2009/09/29/1576380.html
Python library that provides NTLM support, including an authentication handler for urllib2.
This library allows you to retrieve content from (usually corporate) servers protected with windows authentication (NTLM) using the python urllib2.
Python 3 Support
There is work going on to port the library to python 3, you can find it in the python30 directory. (at this time it seems to work as good as the python 2 library)
Usage
Simple example
import urllib2 
from ntlm import HTTPNtlmAuthHandler 
 
user = 'DOMAIN\User' 
password = "Password" 
url = "http://ntlmprotectedserver/securedfile.html" 
 
passman = urllib2.HTTPPasswordMgrWithDefaultRealm() 
passman.add_password(None, url, user, password) 
# create the NTLM authentication handler 
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) 
 
# create and install the opener 
opener = urllib2.build_opener(auth_NTLM) 
urllib2.install_opener(opener) 
 
# retrieve the result 
response = urllib2.urlopen(url) 
print(response.read())

Extended Example
import urllib2 
from urlparse import urlparse, urlunparse 
from ntlm import HTTPNtlmAuthHandler 
 
user = 'DOMAIN\User' 
password = "Password" 
url = "http://ntlmprotectedserver/securedfile.html" 
# determine a base_uri for which the username and password can be used 
parsed_url = urlparse(self.href) 
base_uri = urlunparse((parsed_url[0],parsed_url[1],"","","","")) 
 
passman = urllib2.HTTPPasswordMgrWithDefaultRealm() 
passman.add_password(None, base_uri, user, password) 
# create the NTLM authentication handler 
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) 
 
# other authentication handlers 
auth_basic = urllib2.HTTPBasicAuthHandler(passman) 
auth_digest = urllib2.HTTPDigestAuthHandler(passman) 
 
# disable proxies (if you want to stay within the corporate network) 
proxy_handler = urllib2.ProxyHandler({}) 
 
# create and install the opener 
opener = urllib2.build_opener(proxy_handler, auth_NTLM, auth_digest, auth_basic) 
urllib2.install_opener(opener) 
 
# retrieve the result     
response = urllib2.urlopen(url) 
print(response.read())

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值