2012-11-02 35 views
5

我試圖從需要NTLM登錄的URL中提取信息。Python的NTLM登錄

我收到的淵源401錯誤和一些調整,已經能夠拉頁,指出我輸入憑據無效後。

的用戶名和密碼是正確的但我不能讓過去的憑據無效頁面。

Lgn2.py

import urllib2 
import HTTPNtlmAuthHandler 

login = open('c:/temp/login.txt') 
open = login.read() 
to = open.split() 
user = str(to[0]) 
password = str(to[1]) 

url = "http://INSERT URL HERE.com/" 
passman = urllib2.HTTPPasswordMgrWithDefaultRealm() 
passman.add_password(None, url, user, password) 
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) 


opener = urllib2.build_opener(auth_NTLM) 
urllib2.install_opener(opener) 


response = urllib2.urlopen(url) 
print(response.read()) 

我有包括使用上述的方法我不明白的名稱雙反斜線它打印時\用戶名。我是否應該將它保留在打印文件的名稱中的雙反斜槓上,正如txt文件的用戶名拼寫一樣?

該txt文件只是一個txt文檔,只有:domain \ user \ name密碼

在用戶名的中間的第二反斜線將是用戶名的一部分。

任何幫助,將不勝感激。

+0

http://code.google.com/p/python-ntlm/有一個用戶名,看起來像「域\用戶」。你的用戶名是否有一個域名? –

+0

是的沒有域它會返回401 –

+1

你的網站使用什麼樣的認證機制?如果它沒有設置爲允許基本身份驗證,那麼您必須使用摘要 - 請參閱http://code.google.com/p/python-ntlm/ – Seth

回答

2

也許你沒有使用raw string

除非一個「R」或「R」的前綴是目前,逃避串 序列根據類似於由標準 C中使用的規則解釋。

>>> 'domain\user' 
    File "<stdin>", line 1 
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 6-7: truncated \uXXXX escape 
>>> r'domain\user' 
'domain\\user' 

這個工作對我來說(在Python 2,不是3):

from ntlm import HTTPNtlmAuthHandler 
import urllib2 

user = r'domain\user' 
password = "passphrase" 
passman = urllib2.HTTPPasswordMgrWithDefaultRealm() 
passman.add_password(None, "http://projects/", user, password) 
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) 
opener = urllib2.build_opener(auth_NTLM) 
urllib2.install_opener(opener) 

url = "http://projects/_vti_bin/owssvr.dll?Cmd=Display&List=etc" 
response = urllib2.urlopen(url) 
headers = response.info() 
print("headers: {}".format(headers)) 
body = response.read() 
print("response: " + body) 
+0

上的擴展示例您的帖子非常有用,我也想添加ntlm中的認證頭文件中的變量名是Userauth,請幫幫我 –

+0

謝謝! – bernie

6

我們公司有一個代理並使用NTLM。而不必把憑據腳本我用連接:

import win32com.client 

url = 'https://...' 

h = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1') 
h.SetAutoLogonPolicy(0) 
h.Open('GET', url, False) 
h.Send() 
result = h.responseText 
result 
+0

你在哪裏使用winreg? – Garan

+0

我可能在我的代碼中使用了winreg。我不記得了。我認爲上述工作並不需要。讓我知道你如何繼續。 – toasteez

+0

嗯,它成功地打開了頁面......但事實證明,我們需要在Linux上運行我們的程序,並且自那之後我沒有檢查過它。 – Garan