2011-07-21 42 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为简单和工作示例。 –

相关问题