Skip to content

Commit

Permalink
[FEATURE] First feature
Browse files Browse the repository at this point in the history
- Enable the user to collect the whole inventory information from HBI and Subscription Watch
- Enable the user to filter by `display_name` in the HBI
- The output is by default `JSON`
  • Loading branch information
waldirio authored Aug 11, 2021
1 parent 69d2c2e commit 4849112
Show file tree
Hide file tree
Showing 9 changed files with 411 additions and 4 deletions.
83 changes: 83 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# C.RH.C API Command Line Tool

This project contains the `crhc` command line tool that simplifies the use of the C.RH.C API available at `console.redhat.com`

## Table of Content
- [link](#Binary_File) - You can download the binary file
- [link](#Source_Code) - You can clone the repository and use from the source code
- [link](#Usage) - Usage
- [link](#Contribution) - Contribution

---

## Binary_File
Please, access the release page [here](#) and check the version that you would like to use.

## Source_Code
Please, proceed with the steps below

In your RHEL/CentOS/Fedora/etc with Python 3.x installed, let's execute the commands in a sequence
```
$ git clone https://github.com/C-RH-C/crhc-cli.git
$ cd crhc-cli
$ python3 -m venv ~/.virtualenv/crhc-cli
$ source ~/.virtualenv/crhc-cli/bin/activate
```

Now, you should be in your virtual environment. You can realize your prompt will change
```
(crhc-cli) [user@server crhc-cli]$
```

We can continue
```
(crhc-cli) [user@server crhc-cli]$ pip install -r requirements.txt
```

And finally, we are good to go.
```
(crhc-cli) [user@server crhc-cli]$ ./crhc.py
```

The menu will be as below
```
(crhc-cli) [user@server crhc-cli]$ ./crhc.py
Command line tool for console.redhat.com API
Usage:
crhc [command]
Available Commands:
inventory
swatch
user
Flags:
-h, --help help for crhc
Use "crhc [command] --help" for more information about a command.
```



## Usage

The main idea of this script is to collect the information from `console.redhat.com` in order to generate some reports and/or proceed with some troubleshooting. That said, we can:

- `crhc user set` - To set the credentials that will be used to authenticate on console.redhat.com
- `crhc inventory list` - To list the first 50 entries of your RHEL Inventory
- `crhc inventory list_all` - To list all the entries of your RHEL Inventory
- `crhc inventory --display_name` - To search in RHEL Inventory by `display_name`
- `crhc swatch list` - To list the first 100 entries of your Subscription Watch Inventory
- `crhc swatch list_all` - To list all the entries of your Subscription Watch Inventory

Note. All of them will generate the output in a `JSON` format, so you can use the output as input for any of your own script or also to `jq` command.

## Contribution

I really hope this helps you.

If you need anything else of if you are facing issues trying to use it, please let me know via email or feel free to open a repository issue [here](https://github.com/C-RH-C/crhc-cli/issues)

[email protected] / [email protected]
Empty file added credential/__init__.py
Empty file.
56 changes: 56 additions & 0 deletions credential/credential.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""
Module responsible for set the app credential
"""

import getpass
import os
import sys
import requests


def set_credential():
"""
Responsible to set the credential, create the local file and also validade if the
credential is working as expected
"""
print("setting the credential. At this moment, the credential will be saved as clear text in ~/.crhc.conf")
user = input("Type your console.redhat.com username: ")
password = getpass.getpass("Type your console.redhat.com password: ")

url = "https://console.redhat.com/api/inventory/v1/hosts"
response = requests.get(url, auth=(user, password))

if response.status_code == 200:
print("Authenticated and ready to go!")
else:
print("Please, type again, wrong username or password")
sys.exit()

home_dir = os.path.expanduser('~')
with open(home_dir + "/.crhc.conf", "w") as file_obj:
file_obj.writelines("username:" + user)
file_obj.writelines("\n")
file_obj.writelines("password:" + str(password))


def read_credential():
"""
Responsible to read the credential, and in case the credential is not present yet,
a new file will be created with no valid username and/or password
"""
home_dir = os.path.expanduser('~')

try:
with open(home_dir + "/.crhc.conf", "r") as file_obj:
for line in file_obj:
if 'username' in line:
username = line.split(":")[1]
if 'password' in line:
password = line.split(":")[1]
return username, password
except FileNotFoundError:
home_dir = os.path.expanduser('~')
with open(home_dir + "/.crhc.conf", "w") as file_obj:
file_obj.writelines("username:")
file_obj.writelines("\n")
file_obj.writelines("password:")
10 changes: 6 additions & 4 deletions crhc.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
#!/usr/bin/env python
"""
App responsible for collect some information from
console.redhat.com (Inventory and Subscription Watch)
"""

def main():
print("Here")

from parse import parse

if __name__ == "__main__":
main()
parse.main_menu()
Empty file added execution/__init__.py
Empty file.
93 changes: 93 additions & 0 deletions execution/execution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""
Module responsible for execute all the API calls.
"""

import json
import sys
import requests
from credential import credential

credential_obj = credential.read_credential()

USER = ""
PASSWORD = ""

try:
USER = credential_obj[0]
PASSWORD = credential_obj[1]
except TypeError:
...


def check_authentication(response):
"""
Check if the current credential is valid and authenticating, if not, will
ask for the customer to rerun the command './crhc user set'
"""
if response.status_code != 200:
print("You are not authenticated yet.")
print("Please, use './crhc user set', set the username and password and try again.")
sys.exit()


def inventory_list():
"""
This def will collect the first 50 HBI entries
"""
url = "https://console.redhat.com/api/inventory/v1/hosts"
response = requests.get(url, auth=(USER, PASSWORD))
check_authentication(response)
print(json.dumps(response.json(), indent=4, sort_keys=True))


def inventory_list_all():
"""
This def will collect all the HBI entries
"""
url = "https://console.redhat.com/api/inventory/v1/hosts"
response = requests.get(url, auth=(USER, PASSWORD))
check_authentication(response)
num_of_pages = round(response.json()['total'] / 50 + 1)

for page in range(1, num_of_pages + 1):
url = "https://console.redhat.com/api/inventory/v1/hosts?per_page=50&page=" + str(page)
response = requests.get(url, auth=(USER, PASSWORD))
print(json.dumps(response.json(), indent=4, sort_keys=True))


def inventory_list_search_by_name(fqdn):
"""
This def will search the HBI entries by keyword
"""
url = "https://console.redhat.com/api/inventory/v1/hosts?hostname_or_id=" + fqdn
response = requests.get(url, auth=(USER, PASSWORD))
check_authentication(response)
print(json.dumps(response.json(), indent=4, sort_keys=True))


def swatch_list():
"""
This def will collect the first 100 entries from Subscription Watch
"""
url = "https://console.redhat.com/api/rhsm-subscriptions/v1/hosts/products/RHEL?limit=100&offset=0&sort=display_name"
response = requests.get(url, auth=(USER, PASSWORD))
check_authentication(response)
print(json.dumps(response.json(), indent=4, sort_keys=True))


def swatch_list_all():
"""
This def will collect all the entries from Subscription Watch
"""
url = "https://console.redhat.com/api/rhsm-subscriptions/v1/hosts/products/RHEL?limit=100&offset=0&sort=display_name"
response = requests.get(url, auth=(USER, PASSWORD))
check_authentication(response)
num_of_pages = round(response.json()['meta']['count'] / 100 + 1)

count = 0
for page in range(0, num_of_pages):
url = "https://console.redhat.com/api/rhsm-subscriptions/v1/hosts/products/RHEL?limit=100&offset=" + str(count) + "&sort=display_name"
count = count + 100

response = requests.get(url, auth=(USER, PASSWORD))
print(json.dumps(response.json(), indent=4, sort_keys=True))
Empty file added parse/__init__.py
Empty file.
Loading

0 comments on commit 4849112

Please sign in to comment.