You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将CyberArk SAML认证的PowerShell代码转译为Python?

CyberArk Password Vault SAML认证的Python复刻问题

我需要对CyberArk Password Vault应用执行SAML认证,CyberArk提供的PowerShell代码可成功获取SAML Response令牌以进行后续调用,但目前无法将该代码复刻为Python实现。我最初尝试使用Selenium搭配Edge驱动,但未成功获取SAML Response。PowerShell代码并未使用特定浏览器,请问该如何将其复刻为Python代码?

可成功获取IDP的SAML Response令牌的PowerShell代码

<# ###########################################################################
NAME: CyberArk SAML Authentication via REST API
AUTHOR: Shay Tevet
########################################################################### #>

Add-Type -AssemblyName System.Windows.Forms 
Add-Type -AssemblyName System.Web

$PVWAAddress = "https://passwordvault.acme.net"

function CA_API_SAMLAuth($PVWAAddress)
{    
    $global:tkn = ""
    try{
        $Logon_Body = @{}|ConvertTo-Json
        
        $Logon_URI = "$PVWAAddress/PasswordVault/api/auth/saml/Logon" 
        
        $IdpUrl = Invoke-RestMethod -Uri $Logon_URI -Body $Logon_Body -Method POST -ContentType "application/json" -SessionVariable websession

        $cookies = $websession.Cookies.GetCookies("$PVWAAddress/PasswordVault/api/auth/saml/Logon")
        
        foreach ($cookie in $cookies) { 
            if ($cookie.name -eq "CA88888"){$CA8 = $cookie.value}
        }
    }
    catch{
       Write-Host "StatusMessage:" $_
       return
    }

    try{
        $SAML_Form = New-Object Windows.Forms.Form
        $SAML_Form.StartPosition = 'CenterScreen'
        $SAML_Form.Size = New-Object System.Drawing.Size(650,750) 
       
        $SAML_WB = New-Object Windows.Forms.WebBrowser
        $SAML_WB.Dock = 'Fill'
        $SAML_WB.ScriptErrorsSuppressed = $true

        $SAML_Form.Controls.Add($SAML_WB)

        # Navigate to the IDP URL
        $SAML_WB.Navigate($IdpUrl)

        # Do something before we go anywhere else
        $SAML_WB.add_Navigating({          

            if ($SAML_WB.DocumentText.Contains("SAMLResponse")){

                $_.cancel = $true

                $SAMLElement = $SAML_WB.Document.GetElementsByTagName("input").GetElementsByName("SAMLResponse")[0].GetAttribute("value");

                $SAMLRes = $($SAMLElement -replace ' ', '')

                try{
                    $sessioncc = [Microsoft.PowerShell.Commands.WebRequestSession]::new()

                    $cookie8 = [System.Net.Cookie]::new('CA88888', $CA8)
                    $cookie8.HttpOnly=$true
                    $cookie8.Secure=$true
                    $cookie8.Domain = $PVWAAddress.Split("/")[2]
                    $cookie8.Path = "/"

                    $sessioncc.Cookies.Add($PVWAAddress, $cookie8)
                    
                    $body = @{concurrentSession='true';apiUse='true';SAMLResponse="$($SAMLRes.Trim())"}

                    $contentType = 'application/x-www-form-urlencoded'

                    $SessionToken = Invoke-WebRequest -Method POST -Uri $Logon_URI -body $body -ContentType $contentType  -WebSession $sessioncc

                    $global:tkn = $SessionToken.Content -replace '"', ''
                }
                catch{
                   Write-Host "StatusMessage:" $_
                   return
                }
                $SAML_Form.Close()                
            }
        })

        $SAML_Form.ShowDialog()

        $SAML_Form.Dispose()

        if($global:tkn){
            Write-Host SessionToken: $global:tkn
            return $global:tkn
        }else{
            Write-Host "Something went wrong during the authentication process.\nPlease try signing in again."
            return
        }
    }
    catch{
       Write-Host "StatusMessage:" $_
       return
    }
}


$Token = CA_API_SAMLAuth($PVWAAddress)

我尝试过的Python代码(使用Selenium)

这段代码会在自动化Edge浏览器中弹出MFA提示,但无法像PowerShell代码那样获取SAML Response。我是否需要不通过Edge浏览器,而是用通用框架打开IDP URL并处理SAML重定向?

import time
import os
import re
import urllib.request
import requests
import json

from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import (
    ElementClickInterceptedException,
    NoSuchElementException,
    ElementNotInteractableException,
    SessionNotCreatedException
)

# Webdriver details
ms_edge_webdriver_path = f"C:\\Users\\bugsbunny\\Downloads\\edgedriver_win64\\msedgedriver.exe"

ms_edge_binary_path = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"

pwv_saml_url = f"https://passwordvault.acme.net/PasswordVault/api/auth/saml/Logon"

headers = {
    'Content-Type': 'application/json'
}

initial_pwv_cookie = ""
initial_idp_url = ""

body = {}

with requests.post(pwv_saml_url, headers=headers, verify=False) as initial_idp_response:
    
    initial_idp_url = json.loads(initial_idp_response.content)

    for cookie in initial_idp_response.cookies:
        if cookie.name == "CA88888":
            initial_pwv_cookie = cookie.value

    # --- Setup Selenium Edge driver --- #
    options = Options()

    # 保持浏览器打开
    options.add_experimental_option("detach", True)
    
    # 关闭"个性化你的网页体验"提示
    options.add_experimental_option("prefs",
                                    {"user_experience_metrics": {"personalization_data_consent_enabled": True}})

    # 抑制控制台输出
    options.add_experimental_option('excludeSwitches', ['enable-logging'])

    service = EdgeService(executable_path=ms_edge_webdriver_path)

    driver = webdriver.Edge(service=service, options=options)

    # 最大化窗口
    driver.maximize_window()

    driver.get(initial_idp_url)

内容的提问来源于stack exchange,提问作者Jones Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 07:32:33