> For the complete documentation index, see [llms.txt](https://docs.keeper.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.keeper.io/user-guides/es/import-records-1/import-from-cyberark-pacli.md).

# Importar desde CyberArk PACLI

Importe cuentas de Safes de CyberArk con Microsoft PowerShell y la utilidad PACLI de CyberArk.

<figure><img src="https://914511346-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LSGVtOTYUIkVBoYtFvK%2Fuploads%2Fp1rub66SO3Rvd4Fod9Hh%2FImport-Keeper-Cyberark.jpg?alt=media&#x26;token=2dd2db77-c695-4c77-bcda-68974a31bdf0" alt=""><figcaption></figcaption></figure>

CyberArk incluye una interfaz de línea de comandos, PACLI, que se comunica directamente con el CyberArk Vault. Opera sobre "files" almacenados en "safes" de la bóveda. Puede exportar datos de *account* de CyberArk, que clientes de CyberArk como *PrivateArk* y *Password Vault Web Access (PVWA)* almacenan como *files* en s*afes*.

Las instrucciones siguientes usan un script de PowerShell que utiliza PACLI para exportar todos los archivos que coinciden con un patrón. Con el patrón predeterminado "\*,", exporta todos los archivos del Safe. Extrae Username, Address y password de cada uno; no obstante, se puede configurar para extraer otros campos si es necesario. El script entrega los archivos exportados como objetos; luego se usa ConvertTo-CSV para transformarlos al formato de valores separados por comas (CSV) e importarlos a Keeper.

## Requisitos previos

Para usar el script siguiente se necesitan tres componentes externos:

1. CyberArk PACLI
2. Un archivo de configuración Vault.ini
3. Un archivo de credenciales User.ini

### CyberArk PACLI

PACLI está disponible para descarga en el sitio web de CyberArk Marketplace. Es un archivo zip que contiene el binario `PACLI.exe` y algunos archivos de soporte. El script esperará la ruta del *directorio* que contiene el binario.

### Vault.ini

El archivo vault.ini contiene los parámetros que PACLI necesita para localizar e iniciar sesión en la bóveda. Por ejemplo:

```ini
VAULT=CAMainVault
ADDRESS=10.11.12.13
PREAUTHSECUREDSESSION=YES
TRUSTSSC=YES
```

VAULT normalmente puede dejarse como "CAMainVault."

ADDRESS es el nombre de host o la dirección IP del servidor CyberArk Vault.

Los ajustes PREAUTHSECUREDSESSION y TRUSTSSC son necesarios cuando el usuario de inicio de sesión se autentica mediante LDAP (Active Directory) o RADIUS. De lo contrario, se pueden omitir.

### User.ini

El archivo User.ini está en formato INI. Sin embargo, se genera con la herramienta `CreateCredFile.exe` que CyberArk incluye junto con algunos de sus componentes. Por ejemplo, para generar un user.ini para *Myuser* en el dominio de Active Directory *CORP*:

```powershell
CreateCredFile.exe User.ini Password /Username Myuser /Password "MyPassw0rd!" /ExternalAuth /OSUsername CORP\Myusername
```

La versión más reciente del zip de PACLI incluye la herramienta. Si la ejecuta con el parámetro `/?`, se explicarán las demás opciones útiles en otros escenarios de autenticación.

## Exportar

Pegue lo siguiente en un archivo con extensión *.ps1*, por ejemplo, *Export-CyberArkSafeFiles.ps1*

```powershell
<#
.SYNOPSIS
Exports 'files', i.e., CyberArk Account passwords from a CyberArk Safe using PACLI.

.DESCRIPTION
Uses CyberArk's PACLI command to export files from a CyberArk Safe.
It retrieves files, their categories, and contents and exports an object for each.
It uses filepattern=* to get all files in the safe by default.
The default categories are 'Address' and 'UserName'.
#>
param (
    # The name of the 'Vault' in CyberArk, e.g., 'CAMainVault'
    [Parameter(Mandatory = $true)][string]$VaultName,
    # The name of the 'Safe' in CyberArk
    [Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$SafeName,
    # The CyberArk log on user (must match credentials in the User.ini)
    [Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Username,
    # The path to the PACLI directory containing PACLI.exe
    [Parameter(Mandatory = $true)]
    [ValidateScript({ Test-Path -PathType Leaf (Join-Path $_ 'PACLI.exe') })]
    [string]$PACLIPath,
    # Arguments `findfiles` uses to generate the list of files to export
    [string[]]$FindFilesArguments = 'filepattern=*',
    # The categories to export from the files
    [Parameter()][string[]]$Categories = @('Address', 'UserName'),
    # A CyberArk Vault.ini file
    [Parameter()][ValidateScript({ Test-Path $_ -PathType Leaf })]
    [string]$VaultIniPath = 'Vault.ini',
    # A CyberArk User.ini (or .cred) file as generated by CreateCredFile.exe
    [Parameter()][ValidateScript({ Test-Path $_ -PathType Leaf })]
    [string]$UserIniPath = 'User.ini',
    # The folder in the safe to export files from--most use 'Root'
    [string]$FolderName = 'Root',
    # The session ID to use for the underlying PACLI commands
    [Parameter()][ValidateNotNullOrEmpty()][string]$SessionId,
    # ErrorAction for retrievefile errors
    [Parameter()][ValidateSet('Stop', 'Continue', 'SilentlyContinue')]
    [string]$PACLIErrorAction = 'Continue'
)

$PACLI = Join-Path $PACLIPath 'PACLI.exe' -Resolve

function Invoke-PACLI {
    param (
        [Parameter(Mandatory = $True)][string]$Command,
        [Parameter(ValueFromRemainingArguments)][string[]]$Arguments
    )
    $Executable = ".\{0}" -f (Split-Path -Leaf $PACLI)
    $CommandLine = "$Executable $Command $($Arguments -join ' ')"
    try {
        Push-Location $(Split-Path -Parent $PACLI) -StackName 'PACLI'
        $Output = (& $Executable $Command $Arguments 2>$null)
        if ($LastExitCode -eq 0) {
            $Output
        }
        else {
            switch ($PACLIErrorAction) {
                'Continue' {
                    Write-Error "'$CommandLine' exited with code $LastExitCode"
                }
                'Stop' { throw "'$CommandLine' exited with code $LastExitCode" }
            }
        }
    }
    finally {
        Pop-Location -StackName 'PACLI'
    }
}

Invoke-PACLI init

$PACLIDefaults = "vault=$VaultName", "user=$Username", "safe=$SafeName", 
"folder=$FolderName"
if ($SessionId) {
    $PACLIDefaults += "sessionId=$SessionId"
}
Invoke-PACLI default @PACLIDefaults
Invoke-PACLI definefromfile vault=$VaultName parmfile=(Resolve-Path $VaultIniPath) |
Out-Null
Invoke-PACLI logon logonfile=(Resolve-Path $UserIniPath) | Out-Null
Invoke-PACLI opensafe | Out-Null

try {
    # Create a temporary file to store the file contents during processing
    $tempFile = [IO.Path]::GetTempFileName()
    # Split the tempFile path into the folder and the filename for 'retrievefile'
    $localFolder = Split-Path $tempFile
    $localFile = Split-Path -Leaf $tempFile

    # Get the list of files in the safe
    Invoke-PACLI findfiles $FindFilesArguments 'output(name)' |
    Where-Object { $_.Trim() -ne '' } |
    ForEach-Object {
        $file = @{ Name = $_ }
        # Retrieve the file and store the contents (the password) in the file object
        Invoke-PACLI retrievefile file=$_ localfolder=$localFolder localfile=$localFile
        if ($LastExitCode -ne 0) { return }
        $file.Password = (Get-Content $tempFile).TrimEnd([Char]0) # Can be null-padded
        # Get the list of categories for the file as a quoted CSV string
        Invoke-PACLI listfilecategories file=$_ 'output(all,enclose)' |
        ForEach-Object {
            # Get the category name and value and strip the quotes
            $category = ($_ -split ',' | ForEach-Object { $_.Trim('"') })[0..1]
            # Add the category to the file object if it is on the list
            if ($category[0] -in $Categories) {
                $file[$category[0]] = $category[1]
            }
        }
        [PSCustomObject]$file
    }
}
finally {
    Remove-Item -Path $tempFile -Force
}

Invoke-PACLI closesafe vault=$VaultName user=$Username safe=$SafeName | Out-Null
Invoke-PACLI logoff vault=$VaultName user=$Username | Out-Null
Invoke-PACLI term | Out-Null
```

Extraiga PACLI.zip en el mismo directorio o en un subdirectorio del directorio que contiene el script.

Abra PowerShell y cambie al directorio que contiene el script.

Ejecute el script y envíe la salida a [Export-CSV](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv) (en inglés):

```powershell
.\Export-CyberArkSafeFiles.ps1 CAMainVault MySafe Myuser .\PACLI-Rls-v11.5.3 |
Export-CSV Records.csv -Delimiter "`t" -Encoding utf8 -NoHeader -UseQuotes Never
```

El uso de tabulaciones en lugar de comas, la codificación UTF-8, la exclusión del encabezado y la ausencia de comillas en los datos ayudan a que Keeper importe los datos correctamente.

### Transformación

PowerShell puede transformar los datos más allá de solo darles formato CSV. Este ejemplo más avanzado crea el campo "login" combinando los campos Username y Address, y también lo usa como campo "title".

```powershell
.\Export-CyberArkSafeFiles.ps1 CAMainVault MySafe Myuser .\PACLI-Rls-v11.5.3 |
Select-Object @{l='Folder';e={$_.Name -replace "-$($_.Address)-$($_.Username)", '' }},
 @{l='Login';e={'{0}@{1}' -f $_.Username, $_.Address}}, Password |
Select-Object Folder, @{l='Title';e={$_.Login}}, Login, Password |
Export-Csv Records.csv -Delimiter "`t" -Encoding utf8 -NoHeader -UseQuotes Never
```

## Importar

Siga las instrucciones en [Importar archivo de texto (.csv, .xls, .tsv)](/user-guides/es/import-records-1/import-a-.csv-file.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.keeper.io/user-guides/es/import-records-1/import-from-cyberark-pacli.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
