[轉]關於NTLM認證的.NET,php,python登錄


本文轉自:http://www.cnblogs.com/myx/archive/2013/03/25/php-ntlm-python-net.html

早期SMB協議在網絡上傳輸明文口令。后來出現 LAN Manager Challenge/Response 驗證機制,簡稱LM,它是如此簡單以至很容易就被破解。微軟提出了WindowsNT挑戰/響應驗證機制,稱之為NTLM。現在已經有了更新的NTLMv2以及Kerberos驗證體系。NTLM是windows早期安全協議,因向后兼容性而保留下來。NTLM是NT LAN Manager的縮寫,即NT LAN管理器。NTLM 是為沒有加入到域中的計算機(如獨立服務器和工作組)提供的身份驗證協議。

NTLM驗證允許Windows用戶使用當前登錄系統的身份進行認證,當前用戶應該是登陸在一個域(domain)上,他的身份是可以自動通過瀏覽器傳遞給服務器的。它是一種單點登錄的策略,系統可以通過NTLM重用登錄到Windows系統中的用戶憑證,不用再次要求用戶輸入密碼進行認證。

其實這次要做的功能主要是PHP的NTLM登錄,不過搜索了很久,都沒找到具體的。見到最多資料就是: https://github.com/loune/php-ntlm 不過ntlm_prompt("testwebsite", "testdomain", "mycomputer", "testdomain.local", "mycomputer.local", "get_ntlm_user_hash"); 好像沒有具體的用戶名與密碼,測試的時候還是在游覽器彈出窗口要求輸入用戶名密碼。在其他地方都沒找到可用了。后來看CURL里面有個--ntlm,一測試,原來還這么簡單的。

復制代碼
        $url = 'http://xxxx.com/HomePage/info.aspx';//注意:是要獲取信息的頁面地址,不是登錄頁的地址。 $user ='test'; $password ='testpwd'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); //加上這可以獲取cookies,就是輸出的$result的前面有header信息 curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$password); $result = curl_exec($ch); preg_match_all ('/^Set-Cookie: (.*?);/m',$result,$m); //獲取cookies var_dump($m);
復制代碼

.Net的獲取方式也很簡單,代碼如下:

復制代碼
try { CredentialCache MyCredentialCache = new CredentialCache(); MyCredentialCache.Add(new Uri("http://www.xxx.com/infot.aspx"), "NTLM", new NetworkCredential("test", "testpwd", "domain")); HttpWebRequest req; req = (HttpWebRequest)HttpWebRequest.Create("http://www.xxx.com/info.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); Console.WriteLine("------------------------"); Console.WriteLine(res.Headers.ToString()); if (res.StatusCode == HttpStatusCode.OK) { //驗證成功  Console.WriteLine(res.StatusCode); } } catch (Exception ex) { //驗證失敗  }
復制代碼

Python:python-ntlm(官網地址:http://code.google.com/p/python-ntlm/)是一個用來訪問NTLM認證網址的module, 代碼的那邊搬過來的。我測試可用:

復制代碼
    url = "http://www.xxx.com/info.aspx" #就是注意這個是獲取信息的地址。不是登錄的。剛開始測試用的登錄的地址。那樣是不行的。 user = u'randy\\test' password = 'testpwd' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, url, user, password) # create the NTLM authentication handler auth_NTLM = 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.info()) print(os.path.join(os.getcwd(),"1.txt")) #outfile = open(os.path.join(os.getcwd(),"1.htm"), "w") #outfile.write(response.read())
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM