powershell Cyberark - 自动更改
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell Cyberark - 自动更改相关的知识,希望对你有一定的参考价值。
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True)]
[string]$file,
[Parameter(Mandatory=$True)]
[string]$cred
)
#================================================================================================
# LOAD DLL AES Encrypt
#================================================================================================
#Add-Type -Path "$PSScriptRoot\AESDLL.dll"
[System.Reflection.Assembly]::LoadFrom("D:\Scheduled_Tasks\CyberArkAutoChange\AESDLL.dll")
$hex = New-Object AESClass.cCrypt
#================================================================================================
# functions
#================================================================================================
Function Parse-IniFile ($file)
{
$ini = @{ }
$section = "_NO_SECTION"
$ini[$section] = @{ }
switch -regex (Get-Content $file)
{
'^\[(.+)\]$'
{
$section = $matches[1].Trim()
if (-not $ini.ContainsKey($section)) { $ini[$section] = @{ } }
}
'^\s*([^#\[;].+?)\s*=\s*(.*)'
{
$name, $value = $matches[1 .. 2]
$ini[$section][$name] = $value.Trim()
}
'^\s*([^;\[#][^=]+?)$'
{
$name = $matches[1].Trim()
$value = ''
$ini[$section][$name] = $value.Trim()
}
}
$ini
}
Function WriteLogFile
{
Param ($Message, $checkHost)
$ScriptLogPath = "$PSScriptRoot\Logs\" # + "\Log\"
#Separate Creation Log
if($checkHost)
{
$LogFileName = $checkHost + "_CyberArkWebReq_Created_$cred.txt"
}
else
{
$LogFileName = "CyberArkWebReq_$cred.txt"
}
$path = [System.IO.Path]::Combine($ScriptLogPath, $LogFileName)
$mode = [System.IO.FileMode]::Append
$access = [System.IO.FileAccess]::Write
$fs = New-Object IO.FileStream($path, $mode, $access)
$sw = New-Object System.IO.StreamWriter($fs)
$a = Get-Date
$Now = $a.ToShortDateString() + " " + $a.ToShortTimeString()
$sw.WriteLine("$Now - $Message")
$sw.Close()
$fs.Close()
}
#Initial Variables
Write-Host "file ist $file"
Write-Host "cred ist $cred"
WriteLogFile "[INFORMATION] Credentials zum Anmelden: $cred"
$files = Get-ChildItem -Path D:\WEBROOT\CyberArkRequest\data
#random File picker
$RandomFile = Get-Random -InputObject $files -Count 1
write-host $files -ForegroundColor Green
$fileNotDel = $false
#Decrypt file
$dataToDecrypt = $file
write-host $dataToDecrypt -ForegroundColor Yellow
$hex.HexToString($dataToDecrypt);
$hex.Decrypt(256, $hex.NormalString, "")
$decryptData = $hex.DecryptedString
if($decryptData -eq "4625")
{
WriteLogFile "[ERROR] File $decryptData konnte nicht verschlüsselt werden"
write-host $decryptData -ForegroundColor Red
}
elseif($decryptData -eq "4626")
{
WriteLogFile "[ERROR] File $decryptData konnte nicht entschlüsselt werden"
write-host $decryptData -ForegroundColor Red
}
else
{
#Preparing File for Password Change
$splitFile = $decryptData -split ("_")
$hostname = $splitFile[0]
$domain = ($splitFile[1]).Replace("client.", "")
$ip = $splitFile[2]
WriteLogFile "[INFORMATION] Hostüberprüfung $hostname mit $ip wird druchgeführt"
$HostFQDN = $hostname + "." + $domain
$ADResult = Get-ADComputer $hostname -Server $domain -Properties CanonicalName
$return = $ADResult.CanonicalName.Contains("")
$SpecialComp = Parse-IniFile "D:\Scheduled_Tasks\CyberArkAutoChange\config.ini"
write-host "hostname ist: $hostname" -ForegroundColor Yellow
write-host "domain ist: $domain"
#write-host "safe ist: $CASafe" -ForegroundColor Yellow
$CASafe = $null
$CAPolicy = $null
if(($SpecialComp.ADTeamComp.Values).contains($hostname) -eq $true)
{
$CASafe = ""
$CAPolicy = ""
}
write-host "safe ist: $CASafe" -ForegroundColor Yellow
WriteLogFile "[INFORMATION] $hostname ist im Safe $CASafe abgelegt"
#========================================================================================
# Cyberark Trigger Configuration
#========================================================================================
# configuration file
$ConfigFile = "$PSScriptRoot\autoChangeAccountConfig.xml"
# read configuration file
If (Test-Path $ConfigFile)
{
# config file exists :-) read it!
$cfg = Import-Clixml $ConfigFile
}
Else
{
WriteLogFile "[INFORMATION] $ConfigFile existiert nicht. Es wird ein neues angelegt. Bitte prüfen!"
# config file does not exist :-/ - create it with default values
$cfg = @{}
$cfg.CyberArkUser = "LogonUser"
$cfg.CyberArkVaultName = "Vault"
$cfg.CyberArkPathToPacli = "D:\Cyberark\Pacli\Pacli.exe"
$cfg.CyberArkPathToVaultIni = "D:\Cyberark\Pacli\Vault.ini"
$cfg.PacliDebugOutput = "true"
$cfg | Export-Clixml $ConfigFile
Write-Host "no config file found. created a sample config. please review!"
break
}
# apply config to correct variables for pacli_functions.ps1 to work
#$username = $cfg.CyberArkUser
$username = $cred
$vault = $cfg.CyberArkVaultName
$pacli_path = $cfg.CyberArkPathToPacli
$parm_file = $cfg.CyberArkPathToVaultIni
$output_command = $cfg.PacliDebugOutput
# path configuration
$scriptPath = $PSScriptRoot
$cred_file_path = $scriptPath
$global:logfile = "$scriptPath\Logs\log.txt"
# delete logfile if older than the $limit.
$limit = (Get-Date).AddDays(-5)
if(Test-Path $logfile)
{
$logfile | Where-Object {$_.CreationTime -lt $limit } | Remove-Item -Force
Write-Host "Logfile is olden than $limit - delete"
#WriteLogFile "[WARNING] Logfile is older than $limit - delete"
}
#========================================================================================
# Cyberark Trigger start
#========================================================================================
WriteLogFile "[INFORMATION] Trigger wird nun bearbeitet"
# Include Pacli Functions
."D:\Cyberark\Scripts\Functions\pacli_functions.ps1"
$AccountName = "Administrator@" + $HostFQDN
$Safe = $CASafe
# Log Parameters
writelog $username "i" "============ Start Script ============="
writelog $username "i" "CyberArk User = $username"
writelog $username "i" "CyberArk Vault Name = $vault"
writelog $username "i" "CyberArk Path To Pacli = $pacli_path"
writelog $username "i" "CyberArk Path To Vault.ini = $parm_file"
writelog $username "i" "CREDFILE Path = $cred_file_path"
writelog $username "i" ""
writelog $username "i" "Safe = $Safe"
writelog $username "i" "AccountName = $AccountName"
writelog $username "i" ""
# Check if Pacli Executable is available
test_path $pacli_path
# Initialize PACLI Session
if(pacli_init -eq "failed"){
writelog $username "e" " -- Error on Function PACLI INIT, check Vault Connection"
WriteLogFile "[ERROR] $username e -- Error on Function PACLI INIT, check Vault Connection"
break
}
# Set PACLI defaults
if(pacli_definesafe -eq "failed"){
writelog $username "e" " -- on Function PACLI Definesafe, check Vault Connection"
WriteLogFile "[ERROR] $username e -- on Function PACLI Definesafe, check Vault Connection"
pacli_term
break
}
# Logon on Vault Server
if(pacli_logon $username -eq "failed"){
writelog $username "e" " -- PACLI Logon failed, check credential file"
WriteLogFile "[ERROR] $username e -- PACLI Logon failed, check credential file"
pacli_term
break
}
# Schedule Account for Reconcile (CPM will start reconciliation with next scan as defined in Platform: ImmediateInterval)
writelog $username "i" "Mark Account for Changing Password ..."
# open safe
pacli_open_safe $Safe
# Updating Client IP Address
$UpdateReturn = pacli_filecategory_update $AccountName $Safe "Address" "$HostFQDN"
WriteLogFile "[INFORMATION] Safe überprüfung $UpdateReturn"
#Checking if Account is exists
if($UpdateReturn -match "ITATS053E")
{
$AccountPassword = ""
$AccountUsername = $AccountName.Split("@")[0]
$CA_UserName = $AccountUsername
$CA_DeviceType = "Operating System"
$CA_PolicyID = $CAPolicy
$CA_Description = "Client $hostname"
write-host $CA_UserName
Write-Host $CA_DeviceType
Write-Host $CA_PolicyID
Write-Host $CA_Description
try
{
WriteLogFile "[INFORMATION] Host $hostname is im Safe $CASafe nicht vorhanden"
WriteLogFile "[INFORMATION] Host $hostname wird im Safe $CASafe angelegt"
$ADDAccountState = pacli_add_account $Safe $AccountName $AccountUsername $AccountPassword
#pause;
pacli_filecategory_add $AccountName $Safe "RCH_Description" $CA_Description
#pause;
pacli_filecategory_add $AccountName $Safe "PolicyID" $CA_PolicyID
pacli_filecategory_add $AccountName $Safe "DeviceType" $CA_DeviceType
pacli_filecategory_add $AccountName $Safe "UserName" $CA_UserName
write-host $ADDAccountState -ForegroundColor Yellow
pacli_filecategory_delete $AccountName $Safe "ResetImmediately"
pacli_filecategory_add $AccountName $Safe "RetriesCount" "-1"
pacli_filecategory_add $AccountName $Safe "ResetImmediately" "ReconcileTask"
pacli_filecategory_delete $AccountName $Safe "CPMErrorDetails"
pacli_filecategory_delete $AccountName $Safe "CPMStatus"
pacli_filecategory_delete $AccountName $Safe "RetriesCount"
pacli_filecategory_delete $AccountName $Safe "CPMDisabled"
pacli_filecategory_delete $AccountName $Safe "LastTask"
pacli_filecategory_delete $AccountName $Safe "LastFailDate"
$fileNotDel = $true
}
catch
{
WriteLogFile "[ERROR] Host $hostname konnte im Safe $CASafe nicht angelegt werden" $hostname
}
}
else
{
WriteLogFile "[INFORMATION] Host $hostname is im Safe $CASafe vorhanden"
$fileNotDel = $false
# set for change task
$AccountUsername = $AccountName.Split("@")[0]
$CA_UserName = $AccountUsername
$CA_DeviceType = "Operating System"
$CA_PolicyID = $CAPolicy
$CA_Description = "Client $hostname"
write-host $CA_UserName
Write-Host $CA_DeviceType
Write-Host $CA_PolicyID
Write-Host $CA_Description
pacli_filecategory_add $AccountName $Safe "RCH_Description" $CA_Description
pacli_filecategory_add $AccountName $Safe "PolicyID" $CA_PolicyID
pacli_filecategory_add $AccountName $Safe "DeviceType" $CA_DeviceType
pacli_filecategory_add $AccountName $Safe "UserName" $CA_UserName
pacli_filecategory_delete $AccountName $Safe "ResetImmediately"
pacli_filecategory_add $AccountName $Safe "RetriesCount" "-1"
pacli_filecategory_add $AccountName $Safe "ResetImmediately" "ReconcileTask"
pacli_filecategory_delete $AccountName $Safe "CPMErrorDetails"
pacli_filecategory_delete $AccountName $Safe "CPMStatus"
pacli_filecategory_delete $AccountName $Safe "RetriesCount"
pacli_filecategory_delete $AccountName $Safe "CPMDisabled"
pacli_filecategory_delete $AccountName $Safe "LastTask"
pacli_filecategory_delete $AccountName $Safe "LastFailDate"
}
# close safe
pacli_close_safe $Safe
# Logoff from Vault
pacli_logoff
# Terminate Session
pacli_term
writelog $username "i" "============ Script finished ============="
#WriteLogFile "[SUCCESSFULL] Trigger für den User $AccountName wurde erfolgreich ausgelöst"
#Removing File
$deletefile = Get-ChildItem -Path "D:\WEBROOT\CyberArkRequest\data\$file"
if($fileNotDel -eq $true)
{
$filename = $deletefile.Name
WriteLogFile "[INFORMATION] File not deleted: $filename" $hostname
#WriteLogFile "[INFORMATION] File not deleted: $filename"
}
else
{
$filename = $deletefile.Name
try
{
$deletefile | Remove-Item -Force
WriteLogFile "[INFORMATION] File deleted: $filename"
WriteLogFile "[SUCCESSFULL] Trigger für den User $AccountName wurde erfolgreich ausgelöst"
}
catch
{
$exceptionMessage = $_.exception.message
WriteLogFile "[ERROR] File not deleted: $exceptionMessage"
}
}
}
以上是关于powershell Cyberark - 自动更改的主要内容,如果未能解决你的问题,请参考以下文章
将 CyberPanel 的所有内容迁移到不同 VPS 上的新 CyberPanel