【发布时间】:2016-02-08 22:24:50
【问题描述】:
我想使用 PowerShell 2.0 从包含它的服务器测试我们的 Web 服务器(位于 Intranet 上)是在线 (1) 还是离线 (0)。为此,我有一个脚本可以导航到页面并检查页面上是否有可用的 html 字符串。
function Get-HeartBeat {
$isAlive = $false
try {
$webclient = New-Object WebClient
$userName = "xxx"
$password = "xxx"
$domain = "xxx"
$url = "ourUrl.com"
$html = '<input type="submit">'
$webclient.Credentials = New-Object System.Net.NetworkCredential($userName, $password, $domain)
$webpage = $webclient.DownloadString($url)
$isAlive = $webpage.Contains($html)
} catch {
# A WebException is thrown if the status code is anything but 200 (OK)
Write-Host $_
$isAlive = $false
}
return "$([Int32]$isAlive)"
}
不幸的是,这会返回一个错误:
使用“1”参数调用“DownloadString”的异常:“底层连接已关闭:无法为 SSL/TLS 安全通道建立信任关系。”
信任我们证书的一种方法是创建一个具有如下证书策略的类型(修改this answer):
Add-Type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustOurCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint servicePoint, X509Certificate certificate,
WebRequest request, int certificateProblem)
{
return certificate.Issuer.Equals("OUR ISSUER")
&& certificate.Subject.Contains("our application");
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustOurCertsPolicy
这仍然感觉有点“字符串类型”而不是 100% 安全。
这样安全吗?有没有更好的方法来创建一个接受一个证书的 WebClient?我们应该信任的证书位于cert:LocalMachine\My。
【问题讨论】:
标签: powershell ssl certificate powershell-2.0