2012-03-29 51 views
5

我想在服務器上運行Web抓取腳本。Power Shell Web Scraping SSL/TSL問題

當前腳本收集指定頁面上的html。

$url = "http://websms" 
[net.httpWebRequest] $request = [net.webRequest]::create($url) 
[net.httpWebResponse] $response = $request.getResponse() 
$responseStream = $response.getResponseStream() 
$sr = new-object IO.StreamReader($responseStream) 
$result = $sr.ReadToEnd() 

$result 

這在一個典型的網頁上正常工作。不過,我想在服務器管理頁面上運行它,當然這需要登錄。

我想在我嘗試登錄之前,我會嘗試和颳去服務器的登錄頁面。運行上面的腳本,我得到以下結果。

Exception calling "GetResponse" with "0" argument(s): "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel." 
At C:\temp\web3.ps1:3 char:56 
+ [net.httpWebResponse] $response = $request.getResponse <<<<() 
    + CategoryInfo   : NotSpecified: (:) [], MethodInvocationException 
    + FullyQualifiedErrorId : DotNetMethodException 

如何來解決這個問題,或者是如果你能指出我不同的方向,所以我可以颳去的服務器的管理員HTML頁面元素的任何想法。

謝謝!

回答

23

這一個班輪將忽略SSL證書錯誤:關於自簽名不受信任的證書,不匹配的姓名或到期

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} 

錯誤將在此之後被忽略被執行。

+0

非常感謝! – 2012-03-29 01:54:39

+7

並恢復,只需執行'[System.Net.ServicePointManager] :: ServerCertificateValidationCallback = $ null' – mousio 2012-12-20 14:17:43

+0

非常感謝! – hupseb 2014-06-24 10:07:41

0

使用this brilliant answer

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) 
{ 
    return true; 
} 
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); 
+0

感謝Mathias,可以將它轉換爲Power Shell Script格式嗎? – 2012-03-29 01:33:37

+0

只需在PoSH中運行時從源代碼編譯它,如下所示:http://poshcode.org/624 – 2012-03-29 01:39:30

+0

酷感謝隊友! – 2012-03-29 01:54:52