Skip to content

Commit a4d29eb

Browse files
Merge pull request #21 from VeritasOS/feature/alert_api
Powershell and Python code to get NetBackup alerts.
2 parents 029dbdd + f559007 commit a4d29eb

File tree

3 files changed

+243
-0
lines changed

3 files changed

+243
-0
lines changed
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
<#
2+
3+
.SYNOPSIS
4+
This sample script demonstrates the use of NetBackup REST API for listing the alerts.
5+
6+
.DESCRIPTION
7+
This script will get a list of netbackup alerts and print the details of the latest 10 alerts in a tabular format.
8+
NetBackup supports alerts for VMWare job failures. For more information check help document.
9+
10+
.EXAMPLE
11+
./Get-NB-Alerts.ps1 -nbmaster "nb-master.example.com" -username "administrator" -password "secret"
12+
13+
#>
14+
15+
param (
16+
[string]$nbmaster = $(throw "Please specify the name of NetBackup master server using -nbmaster parameter."),
17+
[string]$username = $(throw "Please specify the user name using -username parameter."),
18+
[string]$password = $(throw "Please specify the password using -password parameter.")
19+
)
20+
21+
#####################################################################
22+
# Initial Setup
23+
# Note: This allows self-signed certificates and enables TLS v1.2
24+
#####################################################################
25+
26+
function InitialSetup()
27+
{
28+
# Allow self-signed certificates
29+
if ([System.Net.ServicePointManager]::CertificatePolicy -notlike 'TrustAllCertsPolicy')
30+
{
31+
Add-Type -TypeDefinition @"
32+
using System.Net;
33+
using System.Security.Cryptography.X509Certificates;
34+
public class TrustAllCertsPolicy : ICertificatePolicy {
35+
public bool CheckValidationResult(
36+
ServicePoint srvPoint, X509Certificate certificate,
37+
WebRequest request, int certificateProblem) {
38+
return true;
39+
}
40+
}
41+
"@
42+
[System.Net.ServicePointManager]::CertificatePolicy = New-Object -TypeName TrustAllCertsPolicy
43+
44+
# Force TLS v1.2
45+
try {
46+
if ([Net.ServicePointManager]::SecurityProtocol -notcontains 'Tls12') {
47+
[Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
48+
}
49+
}
50+
catch {
51+
Write-Host $_.Exception.InnerException.Message
52+
}
53+
}
54+
}
55+
56+
InitialSetup
57+
58+
#####################################################################
59+
# Global Variables
60+
#####################################################################
61+
62+
$port = 1556
63+
$basepath = "https://" + $nbmaster + ":" + $port + "/netbackup"
64+
$content_type = "application/vnd.netbackup+json;version=2.0"
65+
66+
#####################################################################
67+
# Login
68+
#####################################################################
69+
70+
$uri = $basepath + "/login"
71+
72+
$body = @{
73+
userName=$username
74+
password=$password
75+
}
76+
$response = Invoke-WebRequest `
77+
-Uri $uri `
78+
-Method POST `
79+
-Body (ConvertTo-Json -InputObject $body) `
80+
-ContentType $content_type
81+
82+
if ($response.StatusCode -ne 201)
83+
{
84+
$response
85+
throw "Unable to connect to the Netbackup master server!"
86+
}
87+
88+
$content = (ConvertFrom-Json -InputObject $response)
89+
90+
#####################################################################
91+
# Get NetBackup Alerts
92+
#####################################################################
93+
94+
$uri = $basepath + "/manage/alerts"
95+
96+
$headers = @{
97+
"Authorization" = $content.token
98+
}
99+
100+
$query_params = @{
101+
# "page[limit]" = 100 # This changes the default page size to 100
102+
# "filter" = "subCategory eq 'VMWARE'" # This adds a filter to only show the alerts for job failures of VMWARE policy type
103+
}
104+
105+
$response = Invoke-WebRequest `
106+
-Uri $uri `
107+
-Method GET `
108+
-Body $query_params `
109+
-ContentType $content_type `
110+
-Headers $headers
111+
112+
if ($response.StatusCode -ne 200)
113+
{
114+
throw "Unable to get the Netbackup alerts!"
115+
}
116+
117+
$content = (ConvertFrom-Json -InputObject $response)
118+
119+
# This prints all the available attributes
120+
# $content.data.attributes | Format-Table -AutoSize
121+
122+
$properties =
123+
@{Label = "Title"; Expression = { $_.attributes.title }},
124+
@{Label = "Generated At"; Expression = { $_.attributes.createdDateTime }},
125+
@{Label = "Job ID"; Expression = { $_.attributes.params.jobId }},
126+
@{Label = "Status Code"; Expression = { $_.attributes.params.status }},
127+
@{Label = "Error Message"; Expression = { $_.attributes.params.errorMsg }},
128+
@{Label = "Policy Name"; Expression = { $_.attributes.params.policyName }},
129+
@{Label = "Policy Type"; Expression = { $_.attributes.params.policyType }}
130+
131+
$content.data | Format-Table -AutoSize -Property $properties

snippets/python/api_requests.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,5 +54,22 @@ def get_netbackup_jobs(jwt, base_url):
5454

5555
if resp.status_code != 200:
5656
raise Exception('Jobs API failed with status code {} and {}'.format(resp.status_code, resp.json()))
57+
58+
return resp.json()
5759

60+
def get_netbackup_alerts(jwt, base_url):
61+
url = base_url + "/manage/alerts"
62+
headers = {'Content-Type': content_type, 'Authorization': jwt}
63+
query_params = {
64+
# "page[limit]": 100, #This changes the default page size to 100
65+
# "filter":"subCategory eq 'VMWARE'" # This adds a filter to only show the alerts for job failures for VMWARE
66+
}
67+
68+
print("performing GET on {}\n".format(url))
69+
70+
resp = requests.get(url, headers=headers, params=query_params, verify=False)
71+
72+
if resp.status_code != 200:
73+
raise Exception('Alert API failed with status code {} and {}'.format(resp.status_code, resp.json()))
74+
5875
return resp.json()

snippets/python/get_nb_alerts.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import sys
2+
import api_requests
3+
from datetime import datetime
4+
import json
5+
import texttable as tt
6+
import time
7+
8+
protocol = "https"
9+
nbmaster = ""
10+
username = ""
11+
password = ""
12+
port = 1556
13+
14+
def print_alert_details(data):
15+
tab = tt.Texttable()
16+
headings = ['Title', 'Generated At', 'Job ID', 'Status Code', "Error Message","Policy Name","Policy Type"]
17+
tab.header(headings)
18+
19+
for data_item in data:
20+
tuple_value = (
21+
data_item['attributes']['title'],
22+
data_item['attributes']['createdDateTime'],
23+
data_item['attributes']['params']['jobId'],
24+
data_item['attributes']['params']['status'],
25+
data_item['attributes']['params']['errorMsg'],
26+
data_item['attributes']['params']['policyName'],
27+
data_item['attributes']['params']['policyType']
28+
)
29+
tab.add_row(tuple_value)
30+
31+
print(tab.draw())
32+
33+
def print_disclaimer():
34+
print("-------------------------------------------------------------------------------------------------")
35+
print("-- This script requires Python3.5 or higher. --")
36+
print("-- If your current system does not have Python3.5 or higher installed, this will not work. --")
37+
print("-------------------------------------------------------------------------------------------------\n")
38+
print("Executing this library requires some additional python3.5 libraries like \n\t'requests' \n\t'texttable'.\n\n")
39+
print("'texttable' library is just used to show the 'pretty' version of the API response,\nyou might not need it for your netbackup automation.\n")
40+
print("You will, however, require 'requests' library to make the API calls.\n")
41+
print("You can install the dependent libraries using the following commands: ")
42+
print("pip install requests texttable")
43+
print("-------------------------------------------------------------------------------------------------\n\n\n")
44+
print("You can specify the 'nbmaster', 'username' and 'password' as command-line parameters\n")
45+
print_usage()
46+
47+
def print_usage():
48+
print("Example:")
49+
print("python -W ignore get_nb_alerts.py -nbmaster <masterServer> -username <username> -password <password>\n\n\n")
50+
51+
def read_command_line_arguments():
52+
if len(sys.argv)%2 == 0:
53+
print_usage()
54+
exit()
55+
56+
global nbmaster
57+
global username
58+
global password
59+
60+
for i in range(1, len(sys.argv), 2):
61+
if sys.argv[i] == "-nbmaster":
62+
nbmaster = sys.argv[i + 1]
63+
elif sys.argv[i] == "-username":
64+
username = sys.argv[i + 1]
65+
elif sys.argv[i] == "-password":
66+
password = sys.argv[i + 1]
67+
else:
68+
print_usage()
69+
exit()
70+
71+
if nbmaster == "":
72+
print("Please provide the value for 'nbmaster'")
73+
exit()
74+
elif username == "":
75+
print("Please provide the value for 'username'")
76+
exit()
77+
elif password == "":
78+
print("Please provide the value for 'password'")
79+
exit()
80+
81+
print_disclaimer()
82+
83+
read_command_line_arguments()
84+
85+
base_url = protocol + "://" + nbmaster + ":" + str(port) + "/netbackup"
86+
87+
jwt = api_requests.perform_login(username, password, base_url)
88+
89+
alerts = api_requests.get_netbackup_alerts(jwt, base_url)
90+
91+
data = alerts['data']
92+
93+
if len(data) > 0:
94+
print_alert_details(data)
95+

0 commit comments

Comments
 (0)