-
Notifications
You must be signed in to change notification settings - Fork 12
/
rhsmShowConsumerSubs.py
executable file
·164 lines (148 loc) · 7.07 KB
/
rhsmShowConsumerSubs.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
#!/usr/bin/env python
# File: rhsmShowConsumerSubs.py
# Author: Rich Jerrido <[email protected]>
# Purpose: Given a username & password, query
# Red Hat Subscription Management (RHSM) to show a
# listing of consumers and their associated subscriptions
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
import json
import getpass
import urllib2
import base64
import sys
import ssl
import csv
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-l", "--login", dest="login", help="Login user for RHSM", metavar="LOGIN")
parser.add_option("-p", "--password", dest="password", help="Password for specified user. Will prompt if omitted", metavar="PASSWORD")
parser.add_option("-d", "--debug", dest='debug',help="print more details for debugging" , default=False, action='store_true')
parser.add_option("-o", "--output", dest='outputfile',help="output subscriptions to CSV in current directory" , default=False, action='store_true')
parser.add_option("--host", dest='portal_host',help="RHSM host to use (Default subscription.rhsm.redhat.com)" , default="subscription.rhsm.redhat.com")
(options, args) = parser.parse_args()
if not (options.login):
print "Must specify a login (will prompt for password if omitted). See usage:"
parser.print_help()
print "\nExample usage: ./rhsmShowConsumerSubs.py -l rh_user_account "
sys.exit(1)
else:
login = options.login
password = options.password
portal_host = options.portal_host
if not password: password = getpass.getpass("%s's password:" % login)
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context
#### Grab the Candlepin account number
url = "https://" + portal_host + "/subscription/users/" + login + "/owners/"
try:
request = urllib2.Request(url)
if options.debug :
print "Attempting to connect: " + url
base64string = base64.encodestring('%s:%s' % (login, password)).strip()
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
except urllib2.URLError, e:
print "Error: cannot connect to the API: %s" % (e)
print "Check your URL & try to login using the same user/pass via the WebUI and check the error!"
sys.exit(1)
except:
print "FATAL Error - %s" % (e)
sys.exit(2)
accountdata = json.load(result)
for accounts in accountdata:
acct = accounts["key"]
#### Grab a list of Consumers
url = "https://" + portal_host + "/subscription/owners/" + acct + "/consumers/"
if options.debug :
print "Attempting to connect: " + url
try:
request = urllib2.Request(url)
base64string = base64.encodestring('%s:%s' % (login, password)).strip()
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
except urllib2.URLError, e:
print "Error: cannot connect to the API: %s" % (e)
print "Check your URL & try to login using the same user/pass via the WebUI and check the error!"
sys.exit(1)
except:
print "FATAL Error - %s" % (e)
sys.exit(2)
consumerdata = json.load(result)
#### Now that we have a list of Consumers, loop through them and
#### List the subscriptions associated with them.
print "Name, UUID, Consumer Type, Contract Number, Product Name, Start Date, End Date, Quantity, Last Checkin, Username,Sockets,CPUs,IPAddress,Virtual"
if options.outputfile:
csv_writer = csv.writer(open(login + "_inventory_report.csv","wb") , delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
csv_writer.writerow(["Name", "UUID", "Consumer Type", "Contract Number", "Product Name", "Start Date", "End Date", "Quantity", "Last Checkin", "Username" ,"Sockets","CPUs","IPAddress","Virtual"])
for consumer in consumerdata:
consumerType = consumer["type"]["label"]
lastCheckin = consumer["lastCheckin"]
username = consumer["username"]
factsurl = "https://" + portal_host + "/subscription" + consumer["href"] + "/"
if options.debug :
print "Attempting to connect: " + factsurl
try:
sysinfo = urllib2.Request(factsurl)
base64string = base64.encodestring('%s:%s' % (login, password)).strip()
sysinfo.add_header("Authorization", "Basic %s" % base64string)
sysresult = urllib2.urlopen(sysinfo)
sysdata = json.load(sysresult)
except Exception, e:
print "FATAL Error - %s" % (e)
sys.exit(1)
if sysdata['facts'].has_key('virt.is_guest'):
virtis = sysdata['facts']['virt.is_guest']
else:
virtis = "Unknown"
if sysdata['facts'].has_key('network.ipv4_address'):
ipaddr = sysdata['facts']['network.ipv4_address']
else:
ipaddr = "Unknown"
if sysdata['facts'].has_key('cpu.cpu(s)'):
cpus = sysdata['facts']['cpu.cpu(s)']
else:
cpus = "Unknown"
if sysdata['facts'].has_key('cpu.cpu_socket(s)'):
sockets = sysdata['facts']['cpu.cpu_socket(s)']
else:
sockets = "Unknown"
detailedurl = "https://" + portal_host + "/subscription" + consumer["href"] + "/entitlements/"
if options.debug:
print "Attempting to connect: " + url
try:
sysinfo = urllib2.Request(detailedurl)
base64string = base64.encodestring('%s:%s' % (login, password)).strip()
sysinfo.add_header("Authorization", "Basic %s" % base64string)
sysresult = urllib2.urlopen(sysinfo)
sysdata = json.load(sysresult)
except Exception, e:
print "FATAL Error - %s" % (e)
sys.exit(1)
productName = "NA"
contractNumber = "NA"
startDate = "NA"
endDate = "NA"
quantity = "NA"
if sysdata:
for products in sysdata:
productName = products["pool"]["productName"]
contractNumber = products["pool"]["contractNumber"]
startDate = products["startDate"]
endDate = products["endDate"]
quantity = products["quantity"]
print "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" % (consumer["name"],consumer["uuid"],consumerType,contractNumber,productName,startDate,endDate,quantity,lastCheckin,username,sockets,cpus,ipaddr,virtis)
if options.outputfile:
csv_writer.writerow([consumer["name"],consumer["uuid"],consumerType,contractNumber,productName,startDate,endDate,quantity,lastCheckin,username,sockets,cpus,ipaddr,virtis])
else:
print "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" % (consumer["name"],consumer["uuid"],consumerType,contractNumber,productName,startDate,endDate,quantity,lastCheckin,username,sockets,cpus,ipaddr,virtis)
if options.outputfile:
csv_writer.writerow([consumer["name"],consumer["uuid"],consumerType,contractNumber,productName,startDate,endDate,quantity,lastCheckin,username,sockets,cpus,ipaddr,virtis])
sys.exit(0)