-
Notifications
You must be signed in to change notification settings - Fork 3
/
sat6-currency.py
735 lines (666 loc) · 24.8 KB
/
sat6-currency.py
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
#!/usr/bin/python
import argparse
import json
import requests
import sys
import getpass
import os
import yaml
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
parser = argparse.ArgumentParser(
description="Satellite 6 version of 'spacewalk-report system-currency'"
)
parser.add_argument(
"-a", "--advanced",
action="store_true",
default=False,
help="Use this flag if you want to divide security errata by severity."
" Note: this will reduce performance if this script significantly."
)
parser.add_argument(
"-f", "--config",
type=argparse.FileType(mode='r'),
nargs='?',
help="Hammer CLI config file (defaults to ~/.hammer/cli_config.yml",
const=os.path.expanduser('~/.hammer/cli_config.yml')
)
parser.add_argument(
"-n", "--server",
type=str.lower,
help="Satellite server"
)
parser.add_argument(
"-u", "--username",
type=str,
help="Username to access Satellite"
)
parser.add_argument(
"-p", "--password",
type=str,
help="Password to access Satellite."
" The user will be asked interactively if password is not provided."
)
parser.add_argument(
"-s", "--search",
type=str,
required=False,
help="Search string for host."
"( like ?search=lifecycle_environment=Test",
default=('')
)
parser.add_argument(
"-l", "--library",
action="store_true",
required=False,
help="Use this flag to also report on Library Synced Content AND"
" to divide security errata by severity."
" Note: this will reduce performance of this script significantly."
" Use with -o, -e and -c options"
)
parser.add_argument(
"-o", "--organization",
type=str,
required=False,
help="Organization to use when using the '-l' option"
)
parser.add_argument(
"-c", "--contentview",
type=str,
required=False,
default="Default Organization View",
help="Content View to use using the '-l' option."
" Default: Default Organization View"
)
parser.add_argument(
"-e", "--environment",
type=str,
required=False,
default="Library",
help="Environment to use with the '-l' option. Default: Library"
)
args = parser.parse_args()
server = args.server
username = args.username
password = args.password
# If config option specified, read Hammer CLI config file
if args.config is not None:
# Load the configuration file
config = yaml.safe_load(args.config)
# If the key is present in the config file, attempt to load values
# Values specified on the commandline take precendence over config file
key = ':foreman'
try:
if args.server is None:
server = config[key][':host']
else:
server = args.server
except(KeyError):
pass
try:
if args.username is None:
username = config[key][':username']
else:
username = args.username
except(KeyError):
pass
try:
if args.password is None:
password = config[key][':password']
else:
password = args.password
except(KeyError):
pass
if server is None:
raise ValueError("Server was not specified")
if username is None:
raise ValueError("Username was not specified")
if password is None:
password = getpass.getpass()
# Satellite specific parameters
if server.startswith('https://'):
url = server.strip('/')
else:
url = "https://{}".format(server)
api = url + "/api/"
katello_api = url + "/katello/api/v2"
post_headers = {'content-type': 'application/json'}
ssl_verify = True
def get_with_json(location, json_data):
"""
Performs a GET and passes the data to the url location
"""
try:
result = requests.get(
location,
data=json_data,
auth=(username, password),
verify=ssl_verify,
headers=post_headers
)
except requests.ConnectionError, e:
print("{} Couldn't connect to the API,"
" check connection or url".format(location))
print(e)
sys.exit(1)
if result.ok:
return result.json()
else:
print(" Error connecting to '{}'. HTTP Status: {}".format(
location, str(result.status_code)))
sys.exit(1)
def simple_currency():
# Print headline
print(
','.join(str(x) for x in [
"system_id",
"org_name",
"name",
"security",
"bug",
"enhancement",
"score",
"content_view",
"content_view_publish_date",
"lifecycle_environment",
"subscription_os_release",
"os_release",
"arch",
"subscription_status",
"comment"
]
)
)
# Get all hosts (alter if you have more than 10000 hosts)
hosts = get_with_json(
"{}hosts{}".format(api, args.search),
json.dumps({"per_page": "10000"})
)["results"]
# Multiply factors
factor_sec = 8
factor_bug = 2
factor_enh = 1
for host in hosts:
# Check if host is registered with subscription-manager
# (unregistered hosts lack these values and are skipped)
if (
"content_facet_attributes" in host and
host["content_facet_attributes"]["errata_counts"]
):
# Get each number of different kinds of erratas
errata_count_sec = host[
"content_facet_attributes"]["errata_counts"]["security"]
errata_count_bug = host[
"content_facet_attributes"]["errata_counts"]["bugfix"]
errata_count_enh = host[
"content_facet_attributes"]["errata_counts"]["enhancement"]
content_view_name = host[
"content_facet_attributes"]["content_view"]["name"]
content_view_id = host[
"content_facet_attributes"]["content_view"]["id"]
lifecycle_environment = host[
"content_facet_attributes"]["lifecycle_environment"]["name"]
lifecycle_environment_id = host[
"content_facet_attributes"]["lifecycle_environment"]["id"]
subscription_os_release = host[
"subscription_facet_attributes"]["release_version"]
arch = host["architecture_name"]
subscription_status = host["subscription_status_label"]
os_release = host["operatingsystem_name"]
content_view = get_with_json(
"{}/content_views/{}/content_view_versions?"
"environment_id={}".format(
katello_api,
str(content_view_id),
str(lifecycle_environment_id)
),
json.dumps({"per_page": "10000"})
)["results"]
cv_date = content_view[0]["created_at"]
if (
errata_count_sec is None or
errata_count_bug is None or
errata_count_enh is None
):
score = 0
else:
# Calculate weighted score
score = (
errata_count_sec * factor_sec +
errata_count_bug * factor_bug +
errata_count_enh * factor_enh
)
# Print result
print(
','.join(str(x) for x in [
host["id"],
host["organization_name"],
host["name"],
errata_count_sec,
errata_count_bug,
errata_count_enh,
score,
content_view_name,
cv_date,
lifecycle_environment,
subscription_os_release,
os_release,
arch,
subscription_status,
host["comment"],
]
)
)
def advanced_currency():
# Print headline
print(
','.join(str(x) for x in [
"system_id",
"org_name",
"name",
"critical",
"important",
"moderate",
"low",
"bug",
"enhancement",
"score",
"content_view",
"content_view_publish_date",
"lifecycle_environment",
"subscription_os_release",
"os_release",
"arch",
"subscription_status",
"comment"
]
)
)
# Get all hosts (for more than 10000 hosts, this will take a long time)
hosts = get_with_json(
"{}hosts{}".format(api, args.search),
json.dumps({"per_page": "10000"})
)["results"]
# Multiply factors according to "spacewalk-report system-currency"
factor_cri = 32
factor_imp = 16
factor_mod = 8
factor_low = 4
factor_bug = 2
factor_enh = 1
for host in hosts:
# Get all errata for each host
erratas = get_with_json(
"{}hosts/{}/errata".format(api, str(host["id"])),
json.dumps({"per_page": "10000"})
)
# Check if host is registered with subscription-manager
# (unregistered hosts lack these values and are skipped)
if "results" in erratas:
errata_count_cri = 0
errata_count_imp = 0
errata_count_mod = 0
errata_count_low = 0
errata_count_enh = 0
errata_count_bug = 0
# Check if host have any errrata at all
if(
"total" in erratas and
"content_facet_attributes" in host and
"subscription_facet_attributes" in host
):
content_view_name = host[
"content_facet_attributes"]["content_view"]["name"]
content_view_id = host[
"content_facet_attributes"]["content_view"]["id"]
lifecycle_environment = host[
"content_facet_attributes"][
"lifecycle_environment"]["name"]
lifecycle_environment_id = host[
"content_facet_attributes"]["lifecycle_environment"]["id"]
subscription_os_release = host[
"subscription_facet_attributes"]["release_version"]
arch = host["architecture_name"]
subscription_status = host["subscription_status_label"]
os_release = host["operatingsystem_name"]
content_view = get_with_json(
"{}/content_views/{}/content_view_versions?"
"environment_id={}".format(
katello_api,
str(content_view_id),
str(lifecycle_environment_id)
),
json.dumps({"per_page": "10000"})
)["results"]
cv_date = content_view[0]["created_at"]
# Go through each errata
for errata in erratas["results"]:
# If it is a security errata, check the severity
if errata["type"] == "security":
if errata["severity"] == "Critical":
errata_count_cri += 1
if errata["severity"] == "Important":
errata_count_imp += 1
if errata["severity"] == "Moderate":
errata_count_mod += 1
if errata["severity"] == "Low":
errata_count_low += 1
if errata["type"] == "enhancement":
errata_count_enh += 1
if errata["type"] == "bugfix":
errata_count_bug += 1
# Calculate weighted score
score = (
factor_cri * errata_count_cri +
factor_imp * errata_count_imp +
factor_mod * errata_count_mod +
factor_low * errata_count_low +
factor_bug * errata_count_bug +
factor_enh * errata_count_enh
)
# Print result
print(
','.join(str(x) for x in [
host["id"],
host["organization_name"],
host["name"],
errata_count_cri,
errata_count_imp,
errata_count_mod,
errata_count_low,
errata_count_bug,
errata_count_enh,
score,
content_view_name,
cv_date,
lifecycle_environment,
subscription_os_release,
os_release,
arch,
subscription_status,
host["comment"],
]
)
)
def library_currency():
if args.organization is None:
print("Organization must be specified for Library report")
sys.exit(1)
# Print headline
print(
','.join(str(x) for x in [
"system_id",
"org_name",
"name",
"total_available_security",
"critical",
"important",
"moderate",
"low",
"bug",
"enhancement",
"score",
"total_applicable_security",
"applicable_critical",
"applicable_important",
"applicable_moderate",
"applicable_low",
"applicable_bug",
"applicable_enhancement",
"applicable_score",
"content_view",
"content_view_publish_date",
"lifecycle_environment",
"subscription_os_release",
"os_release",
"arch",
"subscription_status",
"comment",
]
)
)
# Open reports files
available_file = open('available_errata.csv', 'w')
available_file.write(
"system_id,org_name,name,state,errata_id,issued,"
"updated,severity,type,reboot_suggested,title,further_info\n"
)
applicable_file = open('applicable_errata.csv', 'w')
applicable_file.write(
"system_id,org_name,name,state,errata_id,issued,"
"updated,severity,type,reboot_suggested,title,further_info\n"
)
# Red Hat errata URL
RH_URL = "https://access.redhat.com/errata/"
# Find organization
organization = get_with_json(
"{}/organizations/?Search={}".format(katello_api, args.organization),
json.dumps({"per_page": "10000"})
)["results"]
organization_id = organization[0]["id"]
# print str(organization_id)
# Find lifecycle_environment
lifecycle_environment_compare = get_with_json(
"{}/organizations/{}/environments?name={}".format(
katello_api, str(organization_id), args.environment),
json.dumps({"per_page": "10000"})
)["results"]
lifecycle_environment_compare_id = lifecycle_environment_compare[0]["id"]
# print str(lifecycle_environment_compare_id)
# Find content view
content_view_compare = get_with_json(
"{}/organizations/{}/content_views?name={}".format(
katello_api, str(organization_id), args.contentview),
json.dumps({"per_page": "10000"})
)["results"]
content_view_compare_id = content_view_compare[0]["id"]
# print str(content_view_compare_id)
# Get all hosts (for more than 10000 hosts, this will take a long time)
hosts = get_with_json(
"{}hosts{}".format(api, args.search),
json.dumps({"per_page": "10000"})
)["results"]
# Multiply factors according to "spacewalk-report system-currency"
factor_cri = 32
factor_imp = 16
factor_mod = 8
factor_low = 4
factor_bug = 2
factor_enh = 1
for host in hosts:
# Get all errata for each host
erratas = get_with_json(
"{}hosts/{}/errata".format(api, str(host["id"])),
json.dumps({"per_page": "10000"})
)
applicable_erratas = get_with_json(
"{}hosts/{}/errata?environment_id={}&content_view_id={}".format(
api,
str(host["id"]),
str(lifecycle_environment_compare_id),
str(content_view_compare_id)
),
json.dumps({"per_page": "10000"})
)
# Check if host is registered with subscription-manager
# (unregistered hosts lack these values and are skipped)
if "results" in erratas:
errata_count_sec = 0
errata_count_cri = 0
errata_count_imp = 0
errata_count_mod = 0
errata_count_low = 0
errata_count_enh = 0
errata_count_bug = 0
applicable_errata_count_sec = 0
applicable_errata_count_cri = 0
applicable_errata_count_imp = 0
applicable_errata_count_mod = 0
applicable_errata_count_low = 0
applicable_errata_count_enh = 0
applicable_errata_count_bug = 0
# Check if host have any errrata at all
if (
"total" in erratas and
"content_facet_attributes" in host and
"subscription_facet_attributes" in host
):
content_view_name = host[
"content_facet_attributes"]["content_view"]["name"]
content_view_id = host[
"content_facet_attributes"]["content_view"]["id"]
lifecycle_environment = host[
"content_facet_attributes"][
"lifecycle_environment"]["name"]
lifecycle_environment_id = host[
"content_facet_attributes"]["lifecycle_environment"]["id"]
subscription_os_release = host[
"subscription_facet_attributes"]["release_version"]
arch = host["architecture_name"]
subscription_status = host["subscription_status_label"]
os_release = host["operatingsystem_name"]
content_view = get_with_json(
"{}/content_views/{}/content_view_versions?"
"environment_id={}".format(
katello_api,
str(content_view_id),
str(lifecycle_environment_id)
),
json.dumps({"per_page": "10000"})
)["results"]
cv_date = content_view[0]["created_at"]
# Go through each errata that is available
for errata in erratas["results"]:
# If it is a security errata, check the severity
if errata["type"] == "security":
errata_count_sec += 1
if errata["severity"] == "Critical":
errata_count_cri += 1
if errata["severity"] == "Important":
errata_count_imp += 1
if errata["severity"] == "Moderate":
errata_count_mod += 1
if errata["severity"] == "Low":
errata_count_low += 1
if errata["type"] == "enhancement":
errata_count_enh += 1
if errata["type"] == "bugfix":
errata_count_bug += 1
# Delete any commas from the errata title
# eg: https://access.redhat.com/errata/RHSA-2017:0817
errata["title"] = errata["title"].replace(',', '')
available_file.write(
','.join(str(x) for x in [
str(host["id"]),
str(host["organization_name"]),
host["name"],
"Available",
str(errata["errata_id"]),
str(errata["issued"]),
str(errata["updated"]),
str(errata["severity"]),
str(errata["type"]),
str(errata["reboot_suggested"]),
str(errata["title"]),
"{}{}\n".format(RH_URL, str(errata["errata_id"])),
]
)
)
# Go through each errata that is applicable (in the library)
for errata in applicable_erratas["results"]:
# If it is a security errata, check the severity
if errata["type"] == "security":
applicable_errata_count_sec += 1
if errata["severity"] == "Critical":
applicable_errata_count_cri += 1
if errata["severity"] == "Important":
applicable_errata_count_imp += 1
if errata["severity"] == "Moderate":
applicable_errata_count_mod += 1
if errata["severity"] == "Low":
applicable_errata_count_low += 1
if errata["type"] == "enhancement":
applicable_errata_count_enh += 1
if errata["type"] == "bugfix":
applicable_errata_count_bug += 1
# Delete any commas from the errata title
# eg: https://access.redhat.com/errata/RHSA-2017:0817
errata["title"] = errata["title"].replace(',', '')
applicable_file.write(
','.join(str(x) for x in [
str(host["id"]),
str(host["organization_name"]),
host["name"],
"Applicable",
str(errata["errata_id"]),
str(errata["issued"]),
str(errata["updated"]),
str(errata["severity"]),
str(errata["type"]),
str(errata["reboot_suggested"]),
str(errata["title"]),
"{}{}\n".format(RH_URL, str(errata["errata_id"])),
]
)
)
# Calculate weighted score
score = (
factor_cri * errata_count_cri +
factor_imp * errata_count_imp +
factor_mod * errata_count_mod +
factor_low * errata_count_low +
factor_bug * errata_count_bug +
factor_enh * errata_count_enh
)
applicable_score = (
factor_cri * applicable_errata_count_cri +
factor_imp * applicable_errata_count_imp +
factor_mod * applicable_errata_count_mod +
factor_low * applicable_errata_count_low +
factor_bug * applicable_errata_count_bug +
factor_enh * applicable_errata_count_enh
)
# Print result
print(
','.join(str(x) for x in [
str(host["id"]),
str(host["organization_name"]),
host["name"],
str(errata_count_sec),
str(errata_count_cri),
str(errata_count_imp),
str(errata_count_mod),
str(errata_count_low),
str(errata_count_bug),
str(errata_count_enh),
str(score),
str(applicable_errata_count_sec),
str(applicable_errata_count_cri),
str(applicable_errata_count_imp),
str(applicable_errata_count_mod),
str(applicable_errata_count_low),
str(applicable_errata_count_bug),
str(applicable_errata_count_enh),
str(applicable_score),
str(content_view_name),
str(cv_date),
str(lifecycle_environment),
str(subscription_os_release),
str(os_release),
str(arch),
str(subscription_status),
str(host["comment"]),
]
)
)
available_file.closed
applicable_file.closed
if __name__ == "__main__":
if args.advanced:
advanced_currency()
sys.exit(0)
if args.library:
library_currency()
sys.exit(0)
else:
simple_currency()