### Link Logon Accounts in CyberArk Vault using Python
Source: https://github.com/safepost/aiobastion/blob/main/docs/started.md
Shows how to retrieve root and admin accounts from multiple safes and programmatically link them based on matching address attributes.
```python
production = aiobastion.EPV("path/to/config.yml")
async with production as vault:
# Returns a list of all root accounts in the safe
root_accounts = await vault.account.search_account_by(safe="linux-safe", username="root")
# Get the logon accounts in two different safes
admin_accounts = await vault.accout.search_account_by(safe="primary-safe", username="admin")
admin_accounts.extend(await vault.accout.search_account_by(safe="other-safe", username="admin"))
# Apply a filter to find the red accounts
for r in root_accounts:
# we search the admin_accounts where the address is equivalent
for a in admin_accounts:
if r.address == a.address:
await vault.account.link_logon_account(r, a)
break
else:
print(f"No logon account found for account with address : {r.address}")
```
--------------------------------
### Aiobastion Configuration File Example (config.yml)
Source: https://context7.com/safepost/aiobastion/llms.txt
Provides a comprehensive example of the `config.yml` file used to configure aiobastion. It includes settings for PVWA, AIM, safe, account, and custom parameters.
```yaml
label: Production Environment
connection:
username: "PVWAUSER001"
authtype: "LDAP" # Cyberark, Windows, LDAP, or RADIUS
user_search:
object: "Operating System-WinDomain-LDAP-PVWAUSER001"
safe: "mysafe"
pvwa:
host: "pvwa.mycompany.com"
timeout: 45
max_concurrent_tasks: 12
verify: true
keep_cookies: false
aim:
appid: "appid_prod"
host: "aim.mycompany.com"
cert: "C:\\Folder\\AIM_cert.pem"
key: "C:\\Folder\\AIM_key.pem"
passphrase: "C3rtP4$$Phr4se"
verify: "C:\\Folder\\Root_ca.crt"
timeout: 45
max_concurrent_tasks: 13
safe:
cpm: "PasswordManager"
retention: 30
account:
logon_account_index: 1
reconcile_account_index: 3
api_options:
deprecated_warning: true
custom:
custom_field1: "value1"
```
--------------------------------
### Verify Red Accounts in CyberArk Vault using Python
Source: https://github.com/safepost/aiobastion/blob/main/docs/started.md
Demonstrates how to search for accounts within a specific safe, filter them based on their CPM status, and trigger a verification process asynchronously.
```python
production = aiobastion.EPV("path/to/config.yml")
async with production as vault:
# Returns a list of all accounts in the safe
safe_account = await vault.account.search_account_by(safe="dba-admin-safe")
# Apply a filter to find the red accounts
red_accounts = [ accounts for accounts in safe_account if not account.cpm_status() ]
# Perform the verify on all those accounts
await vault.account.verify(red_accounts)
```
--------------------------------
### Install Aiobastion Package
Source: https://context7.com/safepost/aiobastion/llms.txt
Installs the aiobastion Python package using pip. This is the first step to using the framework.
```bash
pip install aiobastion
```
--------------------------------
### Platform Details Example Return (JSON)
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
An example JSON structure representing the detailed information returned for a platform, including its active status, system type, allowed safes, privileged access workflows, and credentials management policy.
```JSON
{
"Active":true,
"SystemType":"Database",
"AllowedSafes":".*",
"PrivilegedAccessWorkflows":{
"RequireDualControlPasswordAccessApproval":{
"IsActive":false,
"IsAnException":false
},
"EnforceCheckinCheckoutExclusiveAccess":{
"IsActive":false,
"IsAnException":false
},
"EnforceOnetimePasswordAccess":{
"IsActive":false,
"IsAnException":false
},
"RequireUsersToSpecifyReasonForAccess":{
"IsActive":false,
"IsAnException":false
}
},
"CredentialsManagementPolicy":{
"Verification":{
"PerformAutomatic":false,
"RequirePasswordEveryXDays":7,
"AutoOnAdd":false,
"AllowManual":true
},
"Change":{
"PerformAutomatic":false,
"RequirePasswordEveryXDays":90,
"AutoOnAdd":false,
"AllowManual":true
},
"Reconcile":{
"AutomaticReconcileWhenUnsynced":false,
"AllowManual":true
},
"SecretUpdateConfiguration":{
"ChangePasswordInResetMode":false
}
},
"ID":8,
"PlatformID":"Oracle",
"Name":"Oracle Database"
}
```
--------------------------------
### Complete aiobastion Configuration Example
Source: https://github.com/safepost/aiobastion/blob/main/docs/login.md
This YAML configuration defines all available sections and fields for a comprehensive aiobastion setup. It includes connection details, PVWA and AIM settings, account and safe configurations, API options, and custom parameters. Ensure all paths and credentials are set correctly for your environment.
```yaml
label: Production Demo
connection:
username: "PVWAUSER001"
# password: ""
authtype: "cyberark"
user_search:
object: "Operating System-WinDomain-LDAP-PVWAUSER001"
safe: "mysafe"
folder: "Myfolder"
address: "host_25"
pvwa:
host: "pvwa.mycompany.com"
keep_cookies: false
max_concurrent_tasks: 12
timeout: 45
verify: true
aim:
appid: "appid_prod"
host: "pvwa.acme.fr"
cert: "C:\\Folder\\AIM_file.pem"
# key: "C:\\Folder\\AIM_file.key"
passphrase: "C3rtP4$$Phr4se"
keep_cookies: false
verify: "C:\\Folder\\Root_ca.crt"
timeout: 45
max_concurrent_tasks: 13
account:
logon_account_index: 1
# reconcile_account_index: 3
safe:
cpm: "cpm_user"
retention: 30
api_options:
deprecated_warning: true
custom:
custom1: "info 1"
custom2: "info 2"
```
--------------------------------
### Optimize Account Operations with Batching and Concurrency
Source: https://github.com/safepost/aiobastion/blob/main/docs/started.md
Provides patterns for high-performance account management by dumping safe contents into memory before filtering and using asyncio.gather for concurrent task execution.
```python
# Perform a CPM change a list of accounts for specific host (here host_list) in a specific safe
production = aiobastion.EPV("path/to/config.yml")
async with production as vault:
# Dump all safe in a list of account
admin_accounts = await vault.account.search_account_by(safe="Admins-Accounts-Safe")
# Only accounts whose addresses match our list
filtered_list = [_a for _a in admin_accounts if _a.address in host_list]
# Perform the change
await vault.account.change(filtered_list)
# Good logic for concurrent operations
all_user_list = await self.vault.user.list()
all_user_details = await asyncio.gather(*[self.vault.user.details(_u) for _u in all_user_list])
```
--------------------------------
### Minimal aiobastion Configuration Example
Source: https://github.com/safepost/aiobastion/blob/main/docs/login.md
This minimal YAML configuration only requires the PVWA host to be defined. After setting up this minimal configuration, you must call either the login function or the login_with_aim function to establish a session.
```yaml
PVWA:
Host: "pvwa.mycompany.com"
```
--------------------------------
### HAproxy Load-Balancer Configuration for Testing
Source: https://github.com/safepost/aiobastion/blob/main/CONTRIBUTING.md
Configuration examples for HAproxy to act as a load-balancer for testing. It demonstrates both cookie-based session affinity and hash-based session affinity.
```aidl
backend my_backend
mode http
## cookie based session affinity
cookie SERVERID insert indirect nocache
server backend1 ip_address_1:443 check cookie backend1 ssl verify none
server backend2 ip_address_2:443 check cookie backend2 ssl verify none
# ## hash based session affinity
# stick-table type ip size 200k expire 30m
# stick on src
# server backend1 ip_address_1:443 check ssl verify none
# server backend2 ip_address_2:443 check ssl verify none
```
--------------------------------
### Interactive Export and Delete Multiple Platforms (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
This example provides an interactive way to export and delete platforms. It prompts the user for platform names in a loop until 'exit' is entered. For each platform, it performs an export, retrieves the unique ID, and then deletes the platform, confirming the action.
```python
pf_name = ""
while pf_name != "exit":
pf_name = input("PF name: ")
await epv.platform.export_platform(pf_name, "../../../saved_platforms/")
pf_uid = await epv.platform.get_target_platform_unique_id(pf_name)
await epv.platform.del_target_plaform(pf_uid)
print(f"{pf_name} successfully deleted !")
```
--------------------------------
### GET /platforms/details
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
Retrieves the detailed configuration settings for a specific platform, including password policies, retry intervals, and connection commands.
```APIDOC
## GET /platforms/details
### Description
Retrieves detailed configuration for a specific platform, including security policies and connection parameters.
### Method
GET
### Endpoint
/platforms/details
### Response
#### Success Response (200)
- **PlatformID** (string) - The unique identifier for the platform.
- **Details** (object) - Configuration object containing policy settings.
- **Active** (boolean) - Status of the platform.
#### Response Example
{
"PlatformID":"MySQL",
"Details": {
"PolicyName":"MySQL Server",
"PasswordLength":"12",
"Port":"3306"
},
"Active":false
}
```
--------------------------------
### Login with RADIUS Authentication using Python
Source: https://github.com/safepost/aiobastion/blob/main/docs/login.md
Illustrates how to authenticate with PVWA using RADIUS in a challenge-response mode. This example shows how to catch the ChallengeResponseException and re-attempt login with a passcode. It requires the PVWA host, authentication type, username, and a password obtained securely (e.g., using getpass).
```python
import aiobastion
import asyncio
# import getpass
async async def initialize_pvwa():
pvwa_host = "pvwa.mycompany.com"
authtype = "RADIUS"
username = "PVWAUSER001"
password = getpass.getpass()
global_config = {'api_host': pvwa_host}
epv_env = aiobastion.EPV(serialized=global_config)
try:
await epv_env.login(username=username, password=password, auth_type=authtype)
except ChallengeResponseException:
passcode = input("Enter passcode: ")
await epv_env.login(username=username, password=passcode, auth_type=authtype)
except GetTokenException:
# handle failure here
await epv_env.close_session()
raise
return epv_env
async def somework(epv):
# For example, listing all safes
safes = await epv.safe.list()
for s in safes:
print(s)
async def main():
epv_env = await initialize_pvwa()
# Working with PVWA
async with epv_env as epv:
await somework(epv)
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Get Platform Details by Name (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
Fetches detailed information for a specific platform identified by its name. This is an asynchronous function that returns a dictionary containing the platform's configuration and properties.
```Python
async def get_platforms_details(self, platform_name: str):
"""Get details for a given platform name
* **Parameters:**
**platform_name** – Platform name
* **Returns:**
a dictionary with the details of the platform
"""
pass
```
--------------------------------
### GET /target-platforms/details
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
Retrieves the target platform details, including privileged access workflows and credential management policies.
```APIDOC
## GET /target-platforms/details
### Description
Fetches configuration for target platforms, focusing on privileged access workflows and credential management.
### Method
GET
### Endpoint
/target-platforms/details
### Response
#### Success Response (200)
- **Active** (boolean) - Platform status.
- **SystemType** (string) - The OS or system type.
- **PrivilegedAccessWorkflows** (object) - Workflow configuration settings.
- **CredentialsManagementPolicy** (object) - Policy for verification, change, and reconciliation.
#### Response Example
{
"Active":true,
"SystemType":"*NIX",
"PlatformID":"LinuxDomainAccount",
"Name":"Linux Domain Account"
}
```
--------------------------------
### List Safes using aiobastion in Python
Source: https://github.com/safepost/aiobastion/blob/main/README.md
This Python snippet demonstrates how to log in to a Cyberark PVWA instance and list all available safes. It utilizes the aiobastion library for asynchronous API calls. Ensure you have the aiobastion library installed and provide your PVWA host, login, and password.
```python
import aiobastion
import asyncio
from aiobastion import GetTokenException
async def main():
# Define your PVWA host here
pvwa_host = "pvwa.mycompany.fr"
vault = aiobastion.EPV(serialized={'api_host': pvwa_host})
# Define login and password
login = input("Login: ")
password = input("Password: ")
# Login to the PVWA
try:
await vault.login(login, password)
except GetTokenException as err:
print(f"An error occured while login : {err}")
await vault.close_session()
exit(0)
# Working with PVWA
async with vault as epv:
# For example, listing all safes
safes = await epv.safe.list()
for s in safes:
print(s)
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Get Target Platforms with Criteria (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
Retrieves a list of target platforms based on specified criteria such as active status, system type, and various verification/change/reconciliation settings. If no criteria are provided, it returns all platforms. This function is asynchronous.
```Python
async def get_target_platforms(self, active: bool = None, systemType: str = None, periodicVerify: bool = None, manualVerify: bool = None, periodicChange: bool = None, manualChange: bool = None, automaticReconcile: bool = None, manualReconcile: bool = None):
"""Get target platforms that meet given criteria (or all platforms)
* **Parameters:**
* **active** – Boolean
* **systemType** – str
* **periodicVerify** – Boolean
* **manualVerify** – Boolean
* **periodicChange** – Boolean
* **manualChange** – Boolean
* **automaticReconcile** – Boolean
* **manualReconcile** – Boolean
* **Returns:**
List of target platform dictionaries
"""
pass
```
--------------------------------
### Get Target Platform Details by Name (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
Retrieves detailed information for a single, specific target platform using its name. This asynchronous function returns a dictionary containing the platform's attributes.
```Python
async def get_target_platform_details(self, platform_name: str) -> dict:
"""Give detail about one particular platform
* **Parameters:**
**platform_name** – Name of the platform
* **Returns:**
a dict with details of the platform
"""
pass
```
--------------------------------
### Get Platform Connection Components (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
Retrieves a list of PSM Connectors associated with a given platform unique ID. The platform ID should be the base64 encoded ID obtained via `get_target_platform_unique_id`. This is an asynchronous operation.
```Python
async def get_target_platform_connection_components(self, platformId) -> list:
"""Get the list of PSMConnectors for a platform unique ID
* **Parameters:**
**platformId** – the base64 ID of platform (use get_target_platform_unique_id)
* **Returns:**
a list of connection component
"""
pass
```
--------------------------------
### GET /search_account_by
Source: https://github.com/safepost/aiobastion/blob/main/docs/accounts.md
Searches for accounts in the vault using specific attributes or free-text keywords.
```APIDOC
## GET /search_account_by
### Description
Retrieves a list of account IDs based on specific criteria like username, address, safe, or platform. Note that this does not return the secret password field.
### Method
GET
### Parameters
#### Query Parameters
- **keywords** (string) - Optional - Free search term
- **username** (string) - Optional - Search by userName field
- **address** (string) - Optional - Search by IP address
- **safe** (string) - Optional - Search within a specific safe
- **platform** (string) - Optional - Search by platformId
### Response
#### Success Response (200)
- **accounts** (list) - List of PrivilegedAccount objects
```
--------------------------------
### GET /session-management/policy
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
Retrieves the session management policy, including enabled PSM connectors and server IDs.
```APIDOC
## GET /session-management/policy
### Description
Returns the session management policy configuration, specifically listing enabled PSM connectors.
### Method
GET
### Endpoint
/session-management/policy
### Response
#### Success Response (200)
- **PSMConnectors** (array) - List of enabled PSM connectors.
- **PSMServerId** (string) - The ID of the associated PSM server.
#### Response Example
{
"PSMConnectors":[
{"PSMConnectorID":"PSM-RDP", "Enabled":true}
],
"PSMServerId":"PSMServer"
}
```
--------------------------------
### Integrate aiobastion Async Code in Sync Programs
Source: https://github.com/safepost/aiobastion/blob/main/docs/faq.md
Demonstrates how to execute asynchronous aiobastion functions within a traditional synchronous Python program by utilizing `asyncio.run()`. This pattern is useful for integrating async libraries into existing sync codebases. It covers logging in, performing async tasks, and logging out.
```python
import asyncio
import sys
import time
import aiobastion
from aiobastion import GetTokenException
# Automatic login using configuration setup
async def login_cyberark():
# tests.CONFIG="/path/to/config_file.yml"
epv_env = aiobastion.EPV(tests.CONFIG)
try:
await epv_env.login()
except GetTokenException as err:
raise f"Error while trying to login to the vault : {err}"
return epv_env
async def logoff_cyberark(epv_session):
await epv_session.logoff()
# Some async function that performs tasks into PVWA
async def list_safes(epv):
return await epv.safe.list()
# Sync function
def main():
print("Main program started python", sys.version)
# Async login to Cyberark
epv_session: aiobastion.EPV = asyncio.run(login_cyberark())
# Doing sync stuff
for i in range(3):
time.sleep(0.5)
print(f"Main program iteration {i}")
# Doing async stuff
safes = asyncio.run(list_safes(epv_session))
print(f"List of Safes : {safes}")
# Close connexion at the end, because we don't use context manager
asyncio.run(logoff_cyberark(epv_session))
print("All good !")
if __name__ == "__main__":
main()
```
--------------------------------
### Connect to Account using PSM and Generate RDP File (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/accounts.md
This asynchronous function generates an RDP file for connecting to a privileged account via PSM. It requires account details and a connection component ID. The function returns the RDP file content as bytes. It handles potential Cyberark exceptions during the process.
```python
async with production_vault as epv:
# find first active connexion component
try:
unique_id = await epv.platform.get_target_platform_unique_id(account.platformId)
ccs = await epv.platform.get_target_platform_connection_components(unique_id)
cc = None
for _cc in ccs:
if _cc["Enabled"]:
cc = _cc["PSMConnectorID"]
break
except CyberarkException as err:
# You are not Vault Admin
self.assertIn("PASWS041E", str(err))
rdp_content = await epv.account.connect_using_PSM(account.id, cc)
with open("connect_account.rdp", "w") as rdp_file:
rdp_file.write(rdp_content)
```
--------------------------------
### Connect to CyberArk using Configuration File (Python)
Source: https://context7.com/safepost/aiobastion/llms.txt
Demonstrates connecting to CyberArk using a configuration file (`config.yml`) with aiobastion. It utilizes an asynchronous context manager for automatic login and logout, and lists safes as a test.
```python
import aiobastion
import asyncio
async def main():
# Initialize EPV with configuration file
epv_env = aiobastion.EPV("/path/to/config.yml")
# Automatic login using configuration and auto-logout on exit
async with epv_env as epv:
# List all safes as a simple test
safes = await epv.safe.list()
for s in safes:
print(s)
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### GET /accounts/search
Source: https://context7.com/safepost/aiobastion/llms.txt
Provides multiple methods to search for privileged accounts within the vault, including filtering by safe, username, platform, or custom file categories.
```APIDOC
## GET /accounts/search
### Description
Searches for accounts based on provided criteria. Supports simple filtering, free-text search, pagination, and asynchronous iteration.
### Method
GET
### Parameters
#### Query Parameters
- **safe** (string) - Optional - The name of the safe to search within.
- **username** (string) - Optional - The username to filter by.
- **platform** (string) - Optional - The platform ID to filter by.
- **page** (integer) - Optional - Page number for paginated results.
- **size_of_page** (integer) - Optional - Number of items per page.
### Response
#### Success Response (200)
- **accounts** (array) - List of account objects.
- **has_next_page** (boolean) - Indicates if more results are available.
#### Response Example
{
"accounts": [{"name": "admin", "id": "123"}],
"has_next_page": true
}
```
--------------------------------
### Connect to CyberArk Vault using a context manager
Source: https://github.com/safepost/aiobastion/blob/main/docs/login.md
Demonstrates how to use the aiobastion EPV context manager to handle automatic login and logoff operations using a configuration file.
```python
import aiobastion
import asyncio
async def main():
epv_env = aiobastion.EPV("/path/aiobastion_prod_config.yml")
async with epv_env as epv:
# do something, e.g.:
print(await epv.safe.list())
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Authenticate with manual credential input
Source: https://github.com/safepost/aiobastion/blob/main/docs/login.md
Shows how to initialize an EPV session by manually prompting the user for a username and password, including error handling for the login process.
```python
import aiobastion
import asyncio
import getpass
async def initialize_pvwa():
epv_env = aiobastion.EPV("/path/aiobastion_prod_config.yml")
username = input("Enter CyberArk user: ")
password = getpass.getpass("Enter CyberArk Password: ")
try:
await epv_env.login(username=username, password=password)
except GetTokenException as err:
print(f"An error occured while login : {err}")
await epv_env.close_session()
raise
return epv_env
async def main():
epv_env = await initialize_pvwa()
async with epv_env as epv:
safes = await epv.safe.list()
print(safes)
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Manage AIM Applications with aiobastion
Source: https://context7.com/safepost/aiobastion/llms.txt
Demonstrates how to search, create, configure, and delete AIM applications. It also covers adding various authentication methods such as path, OS user, IP address, hash, and certificate-based authentication.
```python
import aiobastion
import asyncio
async def main():
vault = aiobastion.EPV("/path/to/config.yml")
async with vault as epv:
# Search applications
apps = await epv.application.search("Automation")
print(f"Found apps: {apps}")
# Create new application
await epv.application.add(
app_name="NewAutomationApp",
description="Application for automated password retrieval",
location="\\Applications",
access_from=8,
access_to=20,
expiration="12-31-2025",
disabled=False,
owner_first_name="John",
owner_last_name="Doe",
owner_email="john.doe@company.com",
owner_phone="555-1234"
)
print("Application created")
# Get application details
details = await epv.application.details("NewAutomationApp")
print(f"App details: {details}")
# Add authentication methods
await epv.application.add_authentication(
app_name="NewAutomationApp",
path="/opt/scripts/automation.py",
is_folder=False,
allow_internal_scripts=False
)
await epv.application.add_authentication(
app_name="NewAutomationApp",
os_user="automation_svc"
)
await epv.application.add_authentication(
app_name="NewAutomationApp",
address="192.168.1.100"
)
await epv.application.add_authentication(
app_name="NewAutomationApp",
hash_string="abc123def456...",
comment="automation.py v1.0"
)
await epv.application.add_authentication(
app_name="NewAutomationApp",
serial_number="1234567890",
issuer=["CN=Company CA", "O=Company"],
subject=["CN=automation.company.com"],
subject_alternative_name=["DNS Name=automation.company.com"]
)
# Get authentication methods
auth_methods = await epv.application.get_authentication("NewAutomationApp")
print(f"Auth methods: {auth_methods}")
# Delete application
await epv.application.delete("NewAutomationApp")
print("Application deleted")
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Get CPM Account Status
Source: https://github.com/safepost/aiobastion/blob/main/docs/utilities.md
Retrieves the CPM status for a list of accounts associated with a specific address. It returns a string indicating success (True with the count of good accounts) or failure (False with a list of failed accounts).
```python
async def account_status(self, address: str, accounts: list):
"""Give the CPM status of accounts for an address
:param address: Exact match of address field
:param accounts: List of accounts to get the status for
:return: A string with True and the number of good accounts found, or False with list of failed accounts
"""
pass
```
--------------------------------
### Initialize PVWA Session with AIM Serialization in Python
Source: https://github.com/safepost/aiobastion/blob/main/docs/login.md
This snippet demonstrates how to configure the EPV environment using dictionaries for AIM and PVWA settings. It uses the aiobastion library to perform an asynchronous login and execute tasks within the authenticated session.
```python
import aiobastion
import asyncio
async def initialize_pvwa():
aim_config = {
"appid": "Automation_Application",
"cert": r"C:\Folder\AIM_Cert.pem",
"host": "aim.mycompany.com",
"keep_cookies": False,
"max_concurrent_tasks": 10,
"passphrase": "C3rtP4$$Phr4se",
"timeout": 30,
"verify": r"C:\Folder\AIM_Root_CA.pem"
}
account_config = {
"logon_account_index": 1
}
safe_config = {
"cpm": "PasswordManager",
"retention": 30
}
api_options_config = {
"deprecated_warning": False
}
global_config = {
"api_host": "pvwa.mycompany.com",
"authtype": "LDAP",
"max_concurrent_tasks": 10,
"timeout": 30,
"verify": r"C:\Folder\PVWA_Root_CA.pem",
"keep_cookies": False,
"aim": aim_config,
"account": account_config,
"safe": safe_config,
"api_options": api_options_config
}
epv_env = aiobastion.EPV(serialized=global_config)
username = 'PVWAUSER001'
pvwa_user_search = {
"safe": "production_safe",
"object": "Operating System-WinDomain-LDAP-PVWAUSER001"
}
try:
await epv_env.login(username=username, user_search=pvwa_user_search)
except GetTokenException as err:
await epv_env.close_session()
print(f"Unexpected error: {err}")
raise
return epv_env
async def somework(epv):
safes = await epv.safe.list()
for s in safes:
print(s)
async def main():
epv_env = await initialize_pvwa()
async with epv_env as epv:
await somework(epv)
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Connect to CyberArk with Manual Credentials (Python)
Source: https://context7.com/safepost/aiobastion/llms.txt
Shows how to connect to CyberArk by manually providing username and password, prompting the user when credentials are not in the configuration. Includes error handling for login failures.
```python
import aiobastion
import asyncio
import getpass
from aiobastion import GetTokenException
async def main():
epv_env = aiobastion.EPV("/path/to/config.yml")
# Prompt for credentials
username = input("Enter CyberArk user: ")
password = getpass.getpass("Enter CyberArk Password: ")
try:
await epv_env.login(username=username, password=password)
except GetTokenException as err:
print(f"Login error: {err}")
await epv_env.close_session()
return
async with epv_env as epv:
safes = await epv.safe.list()
print(f"Found {len(safes)} safes")
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Get Target Platform Unique ID (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
Converts a platform identifier (either its ID string like 'WinDesktopLocal' or its name like 'Oracle Database') into its base64 encoded unique ID. This is an asynchronous operation.
```Python
async def get_target_platform_unique_id(self, platformID: str) -> str:
"""Retrieve the base64 ID of a platform
* **Parameters:**
**platformID** – the ID of platform (eg : WinDesktopLocal) or the name (eg “Oracle Database”)
* **Returns:**
base64 ID of the platform
"""
pass
```
--------------------------------
### Get Session Management Policy (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
Fetches the session management policy details for a specific platform. The platform's base64 unique ID, obtained using `get_target_platform_unique_id`, is required. This asynchronous function returns a dictionary of policy information.
```Python
async def get_session_management_policy(self, platformId) -> dict:
"""Get management policy info for a platform
* **Parameters:**
**platformId** – The base64 UD of platform (use get_target_platform_unique_id)
* **Returns:**
a dict with management policy infos
"""
pass
```
--------------------------------
### Create and Delete Users in aiobastion
Source: https://github.com/safepost/aiobastion/blob/main/docs/users.md
Methods for provisioning new users with specific configurations (authentication, location, permissions) and removing existing users from the vault.
```python
async def add(self, username: str, user_type: str = 'EPVUser', **kwargs):
# Creates a new user with optional parameters like password and location
pass
async def delete(self, username: str):
# Removes a user from the vault
pass
```
--------------------------------
### Export All Platforms (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
Asynchronously exports all configured platforms to a specified output directory. This function requires the path to the output directory.
```Python
async def export_all_platforms(self, outdir: str):
pass
```
--------------------------------
### Add Account to Safe (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/accounts.md
Asynchronously creates one or more PrivilegedAccount objects in their designated safe. If an account with the same identifier already exists, a CyberarkAPIException is raised. Supports adding a single account or a list of accounts.
```python
new_account = PrivilegedAccount(userName='testuser', password='testpassword', safe='MySafe', address='10.0.0.5')
account_id = await add_account_to_safe(account=new_account)
```
--------------------------------
### Connect to CyberArk Programmatically (Python)
Source: https://context7.com/safepost/aiobastion/llms.txt
Illustrates initializing an aiobastion EPV connection programmatically without a configuration file. It defines connection parameters, including AIM settings, in a Python dictionary and uses AIM for authentication.
```python
import aiobastion
import asyncio
async def main():
# Define configuration as dictionary
global_config = {
"api_host": "pvwa.mycompany.com",
"authtype": "LDAP",
"max_concurrent_tasks": 10,
"timeout": 30,
"verify": True,
"aim": {
"appid": "Automation_Application",
"cert": "/path/to/cert.pem",
"host": "aim.mycompany.com",
"key": "/path/to/key.pem",
"passphrase": "C3rtP4$$Phr4se",
}
}
epv_env = aiobastion.EPV(serialized=global_config)
# Login with AIM to retrieve PVWA password automatically
await epv_env.login(
username='PVWAUSER001',
user_search={"safe": "production_safe", "object": "PVWAUSER001"}
)
async with epv_env as epv:
safes = await epv.safe.list()
print(f"Connected successfully, found {len(safes)} safes")
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Login with AIM Serialization using Python
Source: https://github.com/safepost/aiobastion/blob/main/docs/login.md
Demonstrates how to log in to PVWA using AIM for retrieving credentials. This method bypasses the need for a configuration file by fetching the PVWA user password directly from the AIM interface. It requires specifying AIM host, application ID, certificate details, and optionally user search parameters if the username is not unique.
```python
import aiobastion
import asyncio
async def initialize_pvwa():
# For demonstration purpose, AIM serialization is not set here
aim_config = None
# PVWA serialization definition, you may specify the following information
global_config = {
"api_host": "pvwa.mycompany.com", # (required) PVWA: Hostname
"authtype": "LDAP", # (optional) PVWA: Defaults is Cyberark. Acceptable values : Cyberark, Windows, LDAP or RADIUS
"max_concurrent_tasks": 10, # (optional) PVWA: Maximum number of parallel task (default 10)
"timeout": 30, # (optional) PVWA: Maximum wait time in seconds before generating a timeout (default 30 seconds)
"verify": true, # (optional) PVWA: set if you want to add additional ROOT ca certs
"aim": aim_config
}
epv_env = aiobastion.EPV(serialized=global_config)
username = 'PVWAUSER001'
# If PVWA username is unique
pvwa_user_search = None
# Or, If PVWA username is not unique, you must specify the user_search parameter.
pvwa_user_search = {
"safe": "production_safe",
"object": "Operating System-WinDomain-LDAP-PVWAUSER001"
}
try:
await epv_env.login_with_aim(
aim_host="aim.mycompany.com",
appid="Automation_Application",
cert_file=r"C:\\Folder\\AIM_Cert.pem",
cert_key=r"C:\\Folder\\AIM_private_key",
passphrase="C3rtP4$$Phr4se",
verify=r"C:\\Folder\\AIM_Root_CA.pem",
# timeout= 30,
# max_concurrent_tasks= 10,
# auth_type="cyberark",
username=username,
user_search=pvwa_user_search)
except GetTokenException as err:
# handle failure here
await epv_env.close_session()
print(f"Unexpected error: {err}")
raise
return epv_env
async def somework(epv):
# For example, listing all safes
safes = await epv.safe.list()
for s in safes:
print(s)
async def main():
epv_env = await initialize_pvwa()
# Working with PVWA
async with epv_env as epv:
await somework(epv)
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Get Account ID from Account Object or String (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/accounts.md
This internal function is used to consistently retrieve the account ID, whether the input is a PrivilegedAccount object or a string account ID. It supports processing a single account or a list containing a mix of account objects and IDs, returning the corresponding account ID(s).
```python
def get_account_id(self, account: PrivilegedAccount | str | List[PrivilegedAccount] | List[str]):
# Implementation details for getting account ID
pass
```
--------------------------------
### Retrieve all connection components via aiobastion
Source: https://github.com/safepost/aiobastion/blob/main/docs/sessionmanagement.md
This asynchronous method fetches a complete list of all connection components currently managed by the system. It returns a list object containing the component details, requiring no input parameters.
```python
async def get_all_connection_components(self):
"""
Returns a list of all connection components.
"""
return await self.api.get("/connection-components")
```
--------------------------------
### Link Logon Account (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/accounts.md
Links an account or a list of accounts to a specified logon account. It's noted that the logon account is expected to have an index of 2. The function returns a boolean indicating success or raises a CyberarkException if the linking fails.
```python
async def link_logon_account(self, account: PrivilegedAccount | List[PrivilegedAccount], logon_account: PrivilegedAccount) -> bool:
"""
This function links the account (or the list of accounts) to the given logon account
⚠️ The “logon” Account is supposed to have an index of 2
* **Parameters:**
* **account** (*PrivilegedAccount* *,* *list*) – a PrivilegedAccount object or a list of PrivilegedAccount objects
* **logon_account** – The logon PrivilegedAccount object
* **Returns:**
A boolean that indicates if the operation was successful.
* **Raises:**
**CyberarkException** – If link failed
"""
pass
```
--------------------------------
### Display Account Count by Platform using Python
Source: https://github.com/safepost/aiobastion/blob/main/docs/platforms.md
This script iterates through all target platforms and performs asynchronous account searches to report the total number of accounts associated with each platform.
```python
async with prod as epv:
pfs = [h['Name'] for h in await epv.platform.get_target_platforms()]
tasks = []
for p in pfs:
tasks.append(epv.account.search_account_by(platform=p))
res = await asyncio.gather(*tasks)
for p,r in zip(pfs,res):
print(f"{p};{len(r)}")
```
--------------------------------
### Update and Delete Accounts with aiobastion
Source: https://context7.com/safepost/aiobastion/llms.txt
Demonstrates how to modify account metadata, update file categories, patch account properties, move accounts between safes, and delete accounts. Requires an initialized EPV instance and a valid account object.
```python
import aiobastion
import asyncio
async def main():
production = aiobastion.EPV("/path/to/config.yml")
async with production as epv:
accounts = await epv.account.search_account_by(safe="my-safe", username="admin")
if accounts:
account = accounts[0]
# Update single file category
await epv.account.update_file_category(
account,
"Environment",
"Production"
)
# Update multiple file categories
await epv.account.update_file_category(
account,
["Environment", "Department"],
["Production", "IT"]
)
# Update platform
await epv.account.update_platform(account, "Unix-SSH-Keys")
# Update using patch operations
data = [
{"path": "/address", "op": "replace", "value": "newserver.company.com"},
{"path": "/platformAccountProperties/CustomFC", "op": "replace", "value": "NewValue"},
]
updated = await epv.account.update_using_list(account, data)
print(f"Updated account: {updated.name}")
# Delete a file category
await epv.account.delete_fc(account, "ObsoleteFC")
# Move account to different safe
await epv.account.move(account, "new-safe")
print("Account moved to new-safe")
# Delete account
await epv.account.delete(account)
print("Account deleted")
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Search Accounts by Free Text (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/accounts.md
Asynchronously searches for accounts using a free-text expression. Returns a list of PrivilegedAccount objects. This is a simpler alternative to `search_account_by` for general text searches.
```python
found_accounts = await search_account(expression="web server admin")
```
--------------------------------
### Search Account by IP Address (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/accounts.md
Asynchronously searches for accounts by their IP address. It validates if the provided address is a valid IPv4 address or a PrivilegedAccount object and then checks the 'address' property of the accounts. Returns a list of matching PrivilegedAccount objects.
```python
ip_address = "192.168.1.100"
matching_accounts = await search_account_by_ip_addr(address=ip_address)
```
--------------------------------
### Create and Configure Safes
Source: https://context7.com/safepost/aiobastion/llms.txt
Provides methods for creating new safes, verifying existence, updating retention/CPM settings, and renaming existing safes.
```python
import aiobastion
import asyncio
async def main():
vault = aiobastion.EPV("/path/to/config.yml")
async with vault as epv:
# Create a new safe
await epv.safe.add(
safe_name="Linux-Production-Safe",
description="Production Linux server credentials",
location="", # Root location
olac=False, # Object Level Access Control
days=30, # Retention days
versions=10, # Number of password versions to keep
cpm="PasswordManager",
add_admins=True # Add default administrators
)
print("Safe created successfully")
# Check if safe exists
exists = await epv.safe.exists("Linux-Production-Safe")
print(f"Safe exists: {exists}")
# Update safe properties
await epv.safe.update(
safe_name="Linux-Production-Safe",
description="Updated description",
days=60,
versions=20,
olac=True
)
# Get safe details
details = await epv.safe.get_safe_details("Linux-Production-Safe")
print(f"Safe details: {details}")
# Rename safe
await epv.safe.rename("Linux-Production-Safe", "Linux-Prod-Safe")
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Link and Unlink Accounts for Password Workflows
Source: https://context7.com/safepost/aiobastion/llms.txt
Shows how to programmatically link logon and reconciliation accounts to target accounts based on address matching. Also demonstrates how to remove these associations when they are no longer required.
```python
import aiobastion
import asyncio
async def main():
production = aiobastion.EPV("/path/to/config.yml")
async with production as epv:
# Get root accounts and admin logon accounts
root_accounts = await epv.account.search_account_by(safe="linux-safe", username="root")
admin_accounts = await epv.account.search_account_by(safe="primary-safe", username="admin")
admin_accounts.extend(
await epv.account.search_account_by(safe="other-safe", username="admin")
)
# Link logon accounts based on matching address
for root_acc in root_accounts:
for admin_acc in admin_accounts:
if root_acc.address == admin_acc.address:
await epv.account.link_logon_account(root_acc, admin_acc)
print(f"Linked logon account for {root_acc.address}")
break
else:
print(f"No logon account found for {root_acc.address}")
# Link reconciliation account
reconcile_accounts = await epv.account.search_account_by(
safe="reconcile-safe",
username="reconcile_admin"
)
if reconcile_accounts:
rec_account = reconcile_accounts[0]
for root_acc in root_accounts:
await epv.account.link_reconciliation_account(root_acc, rec_account)
# Remove linked accounts
account = root_accounts[0]
await epv.account.remove_logon_account(account)
await epv.account.remove_reconcile_account(account)
print("Unlinked logon and reconcile accounts")
if __name__ == '__main__':
asyncio.run(main())
```
--------------------------------
### Retrieve Account Activity and Errors
Source: https://github.com/safepost/aiobastion/blob/main/docs/accounts.md
Methods to fetch the raw activity logs and the most recent CPM error messages associated with privileged accounts.
```python
async def activity(self, account: PrivilegedAccount | List[PrivilegedAccount]):
pass
async def last_cpm_error_message(self, account: PrivilegedAccount | List[PrivilegedAccount]):
pass
```
--------------------------------
### Search Accounts by Multiple Criteria (Python)
Source: https://github.com/safepost/aiobastion/blob/main/docs/accounts.md
Asynchronously searches for accounts using a combination of keywords, username, address, safe, platform, or custom key-value pairs. Returns a list of account IDs. Note that this function does not retrieve the account's secret (password).
```python
accounts = await search_account_by(username="admin", safe="Linux-SRV", my_custom_FC="Database")
```