• 如何让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中运行成功。

     

  • 相关阅读:
    APP自动化测试-8.移动端混合应用自动化测试
    【Java集合类面试十八】、ConcurrentHashMap是怎么分段分组的?
    springboot中使用rabbitmq
    这是什么APP?有谁知道的嘛?
    VB.NET 三层登录系统实战:从设计到部署全流程详解
    easyExcel自定义背景颜色、easyExcel自定义表头背景色
    C#__使用流读取和写入数据的简单用法
    Python学习笔记--类的多态
    HUAWEI Programming Contest 2024(AtCoder Beginner Contest 342)
    ES6 入门教程 15 Proxy 15.2 Proxy 实例的方法 15.2.10 ownKeys() ~ 15.2.12 setPrototypeOf()
  • 原文地址:https://blog.csdn.net/yanghaoji/article/details/125489539