• 如何让PowerShell invoke-restmethod 和 invoke-webrequest 忽略不工作的自签名证书


    invoke-webrequest 和invoke-restmethod 是PowerShell的两个模拟网站请求的命令。不过在一种场景下,它会报错。

     

    Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
        + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

    如何解决:

    有的解决方法是使用这个命令:

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

    但是,如果您使用的是最新版本的Windows 10/2016的Powershell,那么在使用Invoke-RestMethod将会返回:

    Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
    

    为什么会发生这种情况,它可以概括为:

    将ServerCertificateValidationCallback设置为scriptblock将不适用于异步回调(在任务线程上发生的回调),因为另一个线程将没有运行空间来执行脚本.

    这段代码解决了这个问题:这个来处理C#中的证书验证回调而不是脚本块:

    1. function Disable-SslVerification
    2. {
    3. if (-not ([System.Management.Automation.PSTypeName]"TrustEverything").Type)
    4. {
    5. Add-Type -TypeDefinition @"
    6. using System.Net.Security;
    7. using System.Security.Cryptography.X509Certificates;
    8. public static class TrustEverything
    9. {
    10. private static bool ValidationCallback(object sender, X509Certificate certificate, X509Chain chain,
    11. SslPolicyErrors sslPolicyErrors) { return true; }
    12. public static void SetCallback() { System.Net.ServicePointManager.ServerCertificateValidationCallback = ValidationCallback; }
    13. public static void UnsetCallback() { System.Net.ServicePointManager.ServerCertificateValidationCallback = null; }
    14. }
    15. "@
    16. }
    17. [TrustEverything]::SetCallback()
    18. }
    19. function Enable-SslVerification
    20. {
    21. if (([System.Management.Automation.PSTypeName]"TrustEverything").Type)
    22. {
    23. [TrustEverything]::UnsetCallback()
    24. }
    25. }

    windows10中运行成功。

     

  • 相关阅读:
    PyTorch构建分类网络(DNN,Mnist数据集)
    【EI会议征稿】第五届人工智能、网络与信息技术国际学术会议(AINIT 2024)
    MySQL:数据类型和运算符
    【C++】string的接口从生涩到灵活使用——这篇文章就够了
    无影云桌面 1块钱体验
    android 刷机时缺少驱动无法识别
    Redis-带你深入学习数据类型Hash【面试重点】
    AWS SAA C003 #33
    item_get_app(app商品详情原数据)
    自定义注解
  • 原文地址:https://blog.csdn.net/yanghaoji/article/details/125489539