> 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/pt/import-records-1/import-from-cyberark.md).

# Importar do CyberArk PACLI

Importar contas de Safes do CyberArk usando Microsoft PowerShell e o utilitário PACLI do 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>

O CyberArk inclui uma interface de linha de comando, PACLI, que se comunica diretamente com o CyberArk Vault. Ela opera em "files" armazenados em "safes" no vault. Pode exportar dados de *account* do CyberArk, que clientes CyberArk como *PrivateArk* e *Password Vault Web Access (PVWA)* armazenam como *files* em safes.

As instruções abaixo usam um script PowerShell que utiliza o PACLI para exportar todos os arquivos que correspondem a um padrão. Usando o padrão padrão "\*,", ele exporta todos os arquivos do Safe. Extrai Username, Address e password de cada um; no entanto, pode ser configurado para extrair outros campos, se necessário. O script fornece os arquivos exportados como objetos; em seguida, ConvertTo-CSV os transforma em formato Comma-separated Value (CSV) para importá-los no Keeper.

## Pré-requisitos

Três componentes externos são necessários para usar o script abaixo:

1. CyberArk PACLI
2. Um arquivo de configuração Vault.ini
3. Um arquivo de credenciais User.ini

### CyberArk PACLI

O PACLI está disponível para download no site CyberArk Marketplace. É um arquivo zip que contém o binário `PACLI.exe` e alguns arquivos de suporte. O script esperará o caminho do *diretório* que contém o binário.

### Vault.ini

O arquivo vault.ini contém parâmetros que o PACLI precisa para localizar e fazer login no vault. Por exemplo:

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

O VAULT normalmente pode permanecer como "CAMainVault."

O ADDRESS é o hostname ou endereço IP do servidor CyberArk Vault.

As configurações PREAUTHSECUREDSESSION e TRUSTSSC são necessárias quando o usuário de login é autenticado via LDAP (Active Directory) ou RADIUS. Caso contrário, podem ser omitidas.

### User.ini

O arquivo User.ini está no formato INI. No entanto, ele é gerado usando a ferramenta `CreateCredFile.exe` incluída pelo CyberArk em alguns de seus componentes. Por exemplo, gerando um user.ini para *Myuser* no domínio Active Directory *CORP*:

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

A versão mais recente do zip do PACLI contém a ferramenta. Executá-la com o parâmetro `/?` explicará as outras opções úteis em outros cenários de autenticação.

## Exportar

Cole o conteúdo a seguir em um arquivo com extensão *.ps1*, por exemplo, *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
```

Extraia o PACLI.zip no mesmo diretório ou em um subdiretório do diretório que contém o script.

Abra o PowerShell e mude para o diretório que contém o script.

Execute o script e direcione a saída para [Export-CSV](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv) (em 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
```

O uso de tabulações em vez de vírgulas, a codificação UTF-8, a exclusão de cabeçalho e a ausência de aspas nos dados ajudam o Keeper a importar os dados corretamente.

### Transformação

O PowerShell pode ajudar a transformar os dados além de apenas formatá-los como CSV. Este exemplo mais avançado cria o campo "login" combinando os campos Username e Address e também o 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 as instruções em [Importar arquivo de texto (.csv, .xls, .tsv)](/user-guides/pt/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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
