2011-07-21 46 views
5

我正在開發c#應用程序來調用Exchange命令行管理程序Cmdlet。它總是會出現一個例外:「目標計算機上的服務器證書(208.243.XX.2XX:443)出現以下錯誤:
SSL證書由未知證書頒發機構簽署。
SSL證書包含通用名稱(CN)與主機名稱不匹配。「如何忽略SSL證書由未知的證書頒發機構問題簽名?

但我確實編寫了接受所有證書的代碼,不知道爲什麼還是得到錯誤。

我的代碼:

PSCredential credential = new PSCredential("administrator", securePwd); 

    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://208.243.49.20/powershell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential); 
    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic; 

    Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo); 
    PowerShell powershell = PowerShell.Create(); 
    PSCommand command = new PSCommand(); 
    command.AddCommand("New-Mailbox"); 
    command.AddParameter("Name", "TestName"); 
    powershell.Commands = command; 
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(
    delegate { return true; } 
); 
    try 
    { 
     runspace.Open();//This is where the exception happens 
     powershell.Runspace = runspace; 
     Collection<PSObject> result= powershell.Invoke(); 
    } 

回答

2

WSManConnectionInfo對象有兩個屬性可跳過證書檢查。

connectionInfo.SkipCACheck = true; 

connectionInfo.SkipCNCheck = true; 
1

瞎猜:創建運行空間的實例之前可能設置ServicePointManager委託。我只是猜測runpace實例的構造可能會捕獲並存儲來自ServicePointManager的委託。

此外,請確保由代表回答的問題是您的想法。它問的是「有效的證書嗎?」還是問「無效證書?」如果是後者,則將您的委託更改爲{return false; }

最後一件事情是:powershell是否從單獨的進程執行?如果是,則ServicePointManager設置不會對您有所幫助。

+0

感謝您的快速回復。在創建運行空間實例之前,我移動了ServicePointManager,發生了相同的錯誤。我改變返回true返回false,同樣的錯誤。我不確定是否從單獨的進程執行powershell,但似乎ServicePointManager在此過程中沒有任何關係。如果它是一個獨立的過程,那該怎麼辦?提前致謝。 –

+0

你有沒有試過把它作爲第一個命令? –

+0

我越來越相信這是因爲powershell運行在一個單獨的過程中。您需要讓powershell腳本執行與ServicePointManager配置步驟等效的操作。 –

3

我同意Brent,在創建Uri之前,請嘗試將ServicePointManager調用作爲第一次調用。

但是,委託也缺少一些參數。給這個鏡頭:

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; 
+0

嗨邁克,謝謝你的回覆。我把你的代碼放在第一行,仍然有同樣的錯誤。也許它與ServerCertificateValidationCallback無關? –

+0

美麗!它比我以前使用的解決方案更短,並且不需要額外的命名空間導入。 – Colin

3

我認爲布倫特是正確的re:需要在PowerShell過程中。你需要像你的PS下面一行:

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

做對抗不受信任的SSL網站下面的測試,並確認它覆蓋了錯誤:

$url = "https://www.us.army.mil" 
$wc = new-object system.net.webclient 
$x = $wc.downloadstring($url) # will fail 
[System.Net.ServicePointManager]::ServerCertificateValidationCallback += { $true } 
$x = $wc.downloadstring($url) # should succeed 

...這就是說,它是奇怪的是,你說異常發生在打開運行空間時,如果是這種情況,那麼可能不會,因爲你甚至沒有到達PowerShell代碼的執行點。

+0

太棒了!我在PS中測試了你的腳本,就像你說的,我需要它在PS中運行。但我不知道如何在PowerShell過程中添加該行。我寫了command.AddScript(「[System.Net.ServicePointManager] :: ServerCertificateValidationCallback + = {$ true}」);但它不起作用。如何在PS中添加此腳本? –

+0

+1爲簡單和工作示例。 –

相關問題