博客园  :: 首页  :: 联系 :: 订阅 订阅  :: 管理

关于NTLM认证的python和.NET实现

Posted on 2010-03-09 21:56  生鱼片  阅读(2730)  评论(0编辑  收藏  举报

1.NTLM是什么 

早期SMB协议在网络上传输明文口令。后来出现 LAN Manager Challenge/Response 验证机制,简称LM,它是如此简单以至很容易就被破解。微软提出了WindowsNT挑战/响应验证机制,称之为NTLM。现在已经有了更新的NTLMv2以及Kerberos验证体系。NTLMwindows早期安全协议,因向后兼容性而保留下来。NTLMNT LAN Manager的缩写,即NT LAN管理器。NTLM 是为没有加入到域中的计算机(如独立服务器和工作组)提供的身份验证协议。

详细说明可以参考下面资源:

http://baike.baidu.com/view/351131.htm?fr=ala0_1

http://www.hudong.com/wiki/NTLM

http://en.wikipedia.org/wiki/NTLM 

 

2.NTLM验证允许Windows用户使用当前登录系统的身份进行认证,当前用户应该是登陆在一个域(domain)上,他的身份是可以自动通过浏览器传递给服务器的。它是一种单点登录的策略,系统可以通过NTLM重用登录到Windows系统中的用户凭证,不用再次要求用户输入密码进行认证。 

下面是.NET的实现方式,如下: 

static void Main(string[] args)

        {

            try

            {

                CredentialCache MyCredentialCache = new CredentialCache();

                MyCredentialCache.Add(new Uri("http://eip.****.com /default.aspx"), "NTLM", new NetworkCredential("carysun", "****", "******"));

                HttpWebRequest req;

                req = (HttpWebRequest)HttpWebRequest.Create("http://eip.****.com /default.aspx ");

                req.Method = "GET";

                req.KeepAlive = true;

                req.Credentials = MyCredentialCache;

                //保存cookie

                CookieContainer cc = new CookieContainer();

                req.CookieContainer = cc;

                HttpWebResponse res;

                res = (HttpWebResponse)req.GetResponse();

                Console.WriteLine(res.StatusCode);

                if (res.StatusCode == HttpStatusCode.OK)

                {

                    //验证成功

                    Console.WriteLine(res.StatusCode);                

 

                }

            }

            catch (Exception ex)

            {

                //验证失败

 

            }

            Console.ReadLine();

        }

python-ntlm(官网地址:http://code.google.com/p/python-ntlm/)是一个用来访问NTLM认证网址的module。下面是借助该module的实现代码。

import urllib2

from urlparse import urlparse, urlunparse

from ntlm import HTTPNtlmAuthHandler

from urllib2 import Request, urlopen, URLError, HTTPError

 

user = '*****\\carysun'

password = "********"

url = "http://eip.*****.com/default.aspx"

 

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) 

 

req = urllib2.Request(url)

try:

    response = urllib2.urlopen(req)

except HTTPError,e:

    print 'Error code:',e.code

except URLError,e:

    print 'Reason:',e.reason

else:

    print (response.read())