-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAcronisAgentDeployment.ps1
442 lines (341 loc) · 16.3 KB
/
AcronisAgentDeployment.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
<#
.SYNOPSIS
Acronis Agent Deployment
.DESCRIPTION
This PowerShell script is intended to be used in a RMM solution (e. g. Solarwinds N-able RMM or Riversuit Riverbird). The installation files are supposed to be hosted on a secure FTP server.
.INPUTS
No parameters. Variables are supposed to be set by the rmm solution this script is used in.
.OUTPUTS
None
.LINK
https://github.com/MichaelSchoenburg/AcronisAgentDeployment
.LINK
https://developer.acronis.com/doc/account-management/v2/reference/index.html#docs/summary/summary
.LINK
https://www.acronis.com/en-us/blog/posts/how-to-personalize-unattended-acronis-agent-installation-on-windows/
.NOTES
Author: Michael Schönburg
Version: v1.0
This projects code loosely follows the PowerShell Practice and Style guide, as well as Microsofts PowerShell scripting performance considerations.
Style guide: https://poshcode.gitbook.io/powershell-practice-and-style/
Performance Considerations: https://docs.microsoft.com/en-us/powershell/scripting/dev-cross-plat/performance/script-authoring-considerations?view=powershell-7.1
#>
#region FUNCTIONS
<#
Declare Functions
#>
function Write-ConsoleLog {
<#
.SYNOPSIS
Logs an event to the console.
.DESCRIPTION
Writes text to the console with the current date (US format) in front of it.
.PARAMETER Text
Event/text to be outputted to the console.
.EXAMPLE
Write-ConsoleLog -Text 'Subscript XYZ called.'
Long form
.EXAMPLE
Log 'Subscript XYZ called.
Short form
#>
[alias('Log')]
[CmdletBinding()]
param (
[Parameter(Mandatory = $true,
Position = 0)]
[string]
$Text
)
# Save current VerbosePreference
$VerbosePreferenceBefore = $VerbosePreference
# Enable verbose output
$VerbosePreference = 'Continue'
# Write verbose output
Write-Output "$( Get-Date -Format 'MM/dd/yyyy HH:mm:ss' ) - $( $Script:Section ): $( $Text )"
# Restore current VerbosePreference
$VerbosePreference = $VerbosePreferenceBefore
}
function Get-Token {
<#
.SYNOPSIS
Returns an API token.
.DESCRIPTION
Authorize this API client (PowerShell) against the Acronis Account Management API receiving a token. The token is then used to authenticate further API calls.
.PARAMETER Url
URL for your Acronis portal.
.PARAMETER ApiClientId
Client ID for the Acronis Account Management API. This can be generated the Acronis management portal.
.PARAMETER ApiClientSecret
Client secret for the Acronis Account Management API. This too can be generated in the Acronis management portal.
.EXAMPLE
Get-Token -Url 'https://portal.ajani.info' -ApiClientId '02baa9be-f1a2-4524-a8cb-0cd75c9acb61' -ApiClientSecret 'mzrop4shdxil3ud4lvvdcn5l4acqtafufi4juudqabfhxga756pm'
.OUTPUTS
Outputs an array (System.Object) with two variables. First the access token. Secondly the scope.
.NOTES
If you want to use this script for all your clients, you can generate an API client from you partner account which has access to all you clients tenants.
Check the related link for a guid from the manufacturer on how the Acronis Account Management API works and where you can create your API Client ID and secret.
.LINK
https://www.acronis.com/en-us/blog/posts/how-to-automate-acronis-agent-installations/
#>
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]
$Url,
[Parameter(Mandatory)]
[string]
[ValidatePattern('^[A-Za-z0-9]+-[A-Za-z0-9]+-[A-Za-z0-9]+-[A-Za-z0-9]+-[A-Za-z0-9]+$')]
$ApiClientId,
[Parameter(Mandatory)]
[string]
[ValidateLength(52,52)]
$ApiClientSecret
)
# Manually construct Basic Authentication Header
$pair = "${ApiClientId}:${ApiClientSecret}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = @{ "Authorization" = $basicAuthValue }
# Use param to tell type of credentials we request
$postParams = @{ grant_type = "client_credentials" }
# Add the request content type to the headers
$headers.Add("Content-Type", "application/x-www-form-urlencoded")
$headers.Add("User-Agent", "ACP 3.0/Acronis Cyber Platform PowerShell Examples")
$token = Invoke-RestMethod -Method Post -Uri "${Url}api/2/idp/token" -Headers $headers -Body $postParams
# Return access token
return $token
}
#endregion FUNCTIONS
#region INITIALIZATION
<#
Libraries, Modules, ...
#>
# Nothing to initialize this time...
#endregion INITIALIZATION
#region DECLARATIONS
<#
Declare local variables and global variables
#>
# The following variables should be set through your rmm solution.
# Here some examples of possible declarations with explanations for each variable.
# Tip: PowerShell variables are not case sensitive.
<#
$CustomerUserName = 'User'
$CustomerTenantName = "Customer"
$FtpServerFqdn = 'contoso.org' # FQDN or IP address of your FTP server
$FtpUsername = 'user' # Username of your FTP user
$FtpPassword = 'lkj fa8efjalALKJ38uu!"'ÄÖ' # Password for your FTP user
$FtpAgentDir = '\home\BackupAgentInstallFiles\' # Directory in which you've stored the agent installation files
$Dest = 'C:\Installer\Acronis' # Destination where the agent installer should be downloaded/saved to (used to start installation)
$AgentType can be either win, sql, hyperv or ad. If left empty it will auto detect one of the before mentioned.
$Lang = 'de' # Which language should the agent UI use?
$Url = 'https://portal.ajani.info/' # The full URL for your Acronis tenant (plugging Ajani right here)
$ApiClientId = '02baa9be-f1a2-4524-a8cb-0cd75c9acb61' # API client ID
$ApiClientSecret = 'mzrop4shdxil3ud4lvvdcn5l4acqtafufi4juudqabfhxga756pm' # API client secret
$DomAdminUsername = 'DOM\USER'
$DomAdminPassword = 'Pa$$vv0rd'
#>
try {
$Script:Section = 'DECLARATIONS'
$Successful = $false
# The following variables can be adjusted if you have different file names. Names are used to identify the files on the FTP server, as well as to save the downloaded file locally.
$AgentWindows = 'AcronisCyberProtect_AgentForWindows_web.exe' # Full name of the agent installer for windows clients and server
$AgentMsSql = 'AcronisCyberProtect_AgentForSQL_web.exe' # Full name of the agent installer for Microsoft SQL server
$AgentHyperV = 'AcronisCyberProtect_AgentForHyperV_web.exe' # Full name of the agent installer for Microsoft Hyper-V
$AgentAd = 'AcronisCyberProtect_AgentForAD_web.exe' # Full name of the agent installer for Microsoft Active Directory
# Making sure there is a tailing slash in the path
if ( -not ( $Dest.EndsWith('\') ) ){ $Dest = $Dest + '\' }
if ( $FtpAgentDir.Contains('\') ) { $FtpAgentDir = $FtpAgentDir.Replace('\','/') }
if ( -not ( $FtpAgentDir.EndsWith('/') ) ){ $FtpAgentDir = $FtpAgentDir + '/' }
# Default language = German
if (-not $Lang) {
$Lang = 'de'
}
# Agent types
# This doesn't account for a case where multiple of the three roles are installed since I found it to be unlikely
switch ($AgentType) {
win { $AgentName = $AgentWindows }
sql { $AgentName = $AgentMsSql }
hyperv { $AgentName = $AgentHyperV }
ad { $AgentName = $AgentAd }
Default { $DetectAgentType = $true }
}
if ($DetectAgentType) {
try {
if ( (Get-WindowsFeature AD-Domain-Services).Installed ) { Log 'Detected Active Directory.'; $AgentName = $AgentAd }
elseif ( (Get-WindowsFeature Hyper-V).Installed ) { Log 'Detected Hyper-V.'; $AgentName = $AgentHyperV }
} catch {
}
if (-not ($AgentName)) {
if ( Test-Path 'HKLM:\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL' ) { Log 'Detected Microsoft SQL Server.'; $AgentName = $AgentMsSql }
else { Log 'Detected normal Windows.'; $AgentName = $AgentWindows } # If none of the three roles is active, the normal Windows agent will be installed.
}
}
# The following variables can be adjusted if you want a different path/naming
$LogDir = $Dest + 'Log\'
$InstallFile = $Dest + $AgentName
$Source = $FtpAgentDir + $AgentName
#endregion DECLARATIONS
#region EXECUTION
<#
Script entry point
#>
$Script:Section = 'PERQUISITES'
# Check if the agent is already installed. If it is, skip the entire script. If not, proceed with installation.
Log 'Checking if Acronis Cyber Protect Agent is installed already...'
if ((Get-WmiObject -Class Win32_Product -Filter "Name='Cyber Protect'")) {
Log 'Acronis Cyber Protect Agent is installed already. Skipping.'
$Successful = $true
} else {
Log 'Acronis Cyber Protect Agent is not installed. Proceeding...'
<#
Create directory for installation file
#>
Log "Creating directory..."
if (-not (Test-Path -Path $Dest)) {
New-Item -Path $Dest -ItemType Directory -Force
}
<#
Get installation token from API
#>
$Script:Section = 'API'
Log "Issuing API access token..."
# Issue token to access API
$ApiToken = Get-Token -Url $Url -ApiClientId $ApiClientId -ApiClientSecret $ApiClientSecret
$ApiAccessToken = $ApiToken.access_token
Log "Constructing bearer..."
# Manually construct Bearer
$bearerAuthValue = "Bearer $ApiAccessToken"
$headers = @{ "Authorization" = $bearerAuthValue }
Log "Constructing headers..."
# The request contains body with JSON
$headers.Add("Content-Type", "application/json")
$headers.Add("User-Agent", "ACP 3.0/Acronis Cyber Platform PowerShell Examples")
Log "Reading own tenant ID..."
# Get own tenant ID
$apiClientInfo = Invoke-RestMethod -Uri "$($Url)api/2/clients/$($ApiClientId)" -Headers $headers
$tenantId = $apiClientInfo.tenant_id
Log "Reading customer tenant ID..."
# Get customer tenant ID
$pagingParams = @{tenant = $tenantId; text = $customerTenantName}
$searchResult = Invoke-RestMethod -Uri "$($Url)api/2/search" -Headers $headers -Body $pagingParams
if ($searchResult.items.Count -eq 0) {
Log "No acronis tenant of the kind 'customer' with the name '$($customerTenantName)' was found. Aborting script!"
Exit 1
}
$customerTenant = $searchResult.items.Where{($_.obj_type -eq 'tenant') -and ($_.kind -eq 'customer')}
$customerTenantId = $customerTenant.id
Log "Found tenant '$($customerTenant.name)' at path '$($customerTenant.path)' with ID '$($customerTenantId)'."
# Get customer user ID
if ($CustomerUserName) {
# Search for a user with a specific name inside the customers tenant
$pagingParams = @{tenant = $customerTenantId; text = $CustomerUserName}
$searchResult = Invoke-RestMethod -Uri "$($Url)api/2/search" -Headers $headers -Body $pagingParams
# take the first search result
$customerUserId = $searchResult.items[0].id
# Also get full user (details) since not all are included in the search result
$pagingParams = @{uuids = $customerUserId}
$result = Invoke-RestMethod -Uri "$($Url)api/2/users" -Headers $headers -Body $pagingParams
$customerUser = $result.items[0]
} else {
# Get all users that exists inside the customer tenant
$customerUserIds = Invoke-RestMethod -Uri "$($Url)api/2/tenants/$($customerTenantId)/users" -Headers $headers
# Take the first user
$customerUserId = $customerUserIds.items[0]
# Also get full user (details) instead of just the user ID
$pagingParams = @{uuids = $customerUserId}
$result = Invoke-RestMethod -Uri "$($Url)api/2/users" -Headers $headers -Body $pagingParams
$customerUser = $result.items[0]
}
Log "Found user with login '$($customerUser.login)' with ID '$($customerUser.id)' and personal tenant ID '$($customerUser.personal_tenant_id)' in tenant '$($customerUser.tenant_id)'."
if ($customerUser.enabled) {
Log 'This user is enabled.'
} else {
Log "This user isn't enabled. Aborting script!"
Exit 1
}
if ($customerUser.activated) {
Log 'This user is activated.'
} else {
Log "This user isn't activated. Aborting script!"
Exit 1
}
# Get personal tenant ID of the customers user
$pagingParams = @{uuids = $customerUserId}
$user = Invoke-RestMethod -Uri "$($Url)api/2/users" -Headers $headers -Body $pagingParams
$personalTenantId = $user.items.personal_tenant_id
# Issue a token
$bearerAuthValue = "Bearer $ApiAccessToken"
$headers = @{ "Authorization" = $bearerAuthValue }
$headers.Add("Content-Type", "application/json")
$headers.Add("User-Agent", "ACP 3.0/Acronis Cyber Platform PowerShell Examples")
$json = @{
'expires_in' = 3600
'scopes' = @( "urn:acronis.com:tenant-id:$($personalTenantId):backup_agent_admin" )
}
$json = $json | ConvertTo-Json
$ClientRegistration = Invoke-RestMethod -Method Post -Uri "$($Url)api/2/tenants/$($customerTenantId)/registration_tokens" -Headers $headers -Body $json
<#
Connect to FTP server to receive installation file
#>
$Script:Section = "FTP"
# Check if PowerShell module for SFTP is installed already
if (Get-Module -Name Posh-SSH) {
Log 'Module "Posh-SSH" already imported'
} elseif (Get-Module -Name Posh-SSH -ListAvailable) {
Log 'Module installed already.'
Log 'Importing Module "Posh-SSH"...'
Import-Module -Name Posh-SSH
} else {
if (-not (Get-PackageProvider -Name NuGet) ) {
Log 'Installing NuGet...'
Install-PackageProvider -Name NuGet -Force
}
Log 'Installing Module "Posh-SSH"...'
Install-Module -Name Posh-SSH -Force
Log 'Importing Module "Posh-SSH"...'
Import-Module -Name Posh-SSH
}
# Build credentials for FTP server
$SecureString = ConvertTo-SecureString -AsPlainText $FtpPassword -Force
$Creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $FtpUsername,$SecureString
try {
# Connect to FTP server
$s = New-SFTPSession -ComputerName $FtpServerFqdn -Credential $Creds -Port 22 -AcceptKey:$true
# Download installation file
Get-SFTPItem -SFTPSession $s -Path $Source -Destination $Dest -Force # One can only specify a directory as destination. The file will always keep its name.
} finally {
# Disconnect from FTP server
Remove-SFTPSession -SFTPSession $s
}
<#
Install
#>
$Script:Section = "INSTALL"
# Execute installation file with arguments
# I decided not to wait for the process.
# If I waited I might run into a timeout with the RMM script runner.
Log 'Starting installation...'
if ($AgentName -eq $AgentAd) {
& $InstallFile --quiet --language=$Lang --reg-token=$( $ClientRegistration.token ) --log-dir=$LogDir --reg-address=$Url --agent-account-login=$DomAdminUsername --agent-account-password=$DomAdminPassword
} else {
& $InstallFile --quiet --language=$Lang --reg-token=$( $ClientRegistration.token ) --log-dir=$LogDir --reg-address=$Url
}
$Successful = $true
}
} catch {
Log "Exception Message: $($PSItem.Exception.Message)"
Log "Inner Exception Message: $($PSItem.Exception.InnerException)"
$PSItem.InvocationInfo | Format-List *
} finally {
if ($Successful) {
Log "`$Successful is set to true. Exiting with exit code 0."
Exit 0
} else {
Log "`$Successful isn't set to true. Exiting with exit code 1."
Exit 1
}
}
#endregion EXECUTION