[PYTHON] Operate Nutanix with REST API Part 2

Operate Nutanix with REST API Part 2

table of contents

Script overview

Purpose

Program flow

Make little by little

Script for checking the main process

import requests
import urllib3
from urllib3.exceptions import InsecureRequestWarning
urllib3.disable_warnings(InsecureRequestWarning)
import json

IP = '10.42.8.37'
USER = 'admin'
PASSWORD = 'hogehoge'

# (1) Make Session
session = requests.Session()
session.auth = (USER, PASSWORD)
session.verify = False                              
session.headers.update({'Content-Type': 'application/json; charset=utf-8'})

# (2) Make URL
url = 'https://{}:9440/PrismGateway/services/rest/v1/cluster'.format(IP)

# (3) Send request and get Response
response = session.get(url)

# (4) Check response code
print('Response Code: {}'.format(response.status_code))
print('Response OK?: {}'.format(response.ok))

# (5) Check response body
print('Response Body:')
print(response.text)


Script description

import process. Set when doing something using http communication

import requests
import urllib3
from urllib3.exceptions import InsecureRequestWarning
urllib3.disable_warnings(InsecureRequestWarning)
import json

Creating and initializing session objects

IP = '10.42.8.37'
USER = 'admin'
PASSWORD = 'hogehoge'

# (1) Make Session
session = requests.Session()
session.auth = (USER, PASSWORD)
session.verify = False                              
session.headers.update({'Content-Type': 'application/json; charset=utf-8'})

# (2) Make URL
url = 'https://{}:9440/PrismGateway/services/rest/v1/cluster'.format(IP)

Session execution

# (3) Send request and get Response
response = session.get(url)

# (4) Check response code
print('Response Code: {}'.format(response.status_code))
print('Response OK?: {}'.format(response.ok))

# (5) Check response body
print('Response Body:')
print(response.text)

The completed script

import requests
import urllib3
from urllib3.exceptions import InsecureRequestWarning
urllib3.disable_warnings(InsecureRequestWarning)
import json
import base64

#Read file
fin = open('cvm_info.json', 'r')

#Read server information
# IP = '10.42.8.37'
# USER = 'admin'
# PASSWORD = 'pass'

sv_info = json.load(fin)
IP = sv_info['cluster_address']
USER = sv_info['user_name']
PASSWORD = sv_info['cvm_password']
fin.close()

auth_str = USER + ':' + PASSWORD
auth_str = api_head = {
    'Authorization': 'Basic ' + base64.b64encode(auth_str.encode('utf-8')).decode(),
}

# (1) Make Session
session = requests.Session()
session.auth = (USER, PASSWORD)
session.verify = False                              
session.headers.update({'Content-Type': 'application/json; charset=utf-8'})

# (2) Make URL
url = 'https://{}:9440/PrismGateway/services/rest/v2.0/vms/'.format(IP)

# (3) Send request and get Response
response = session.get(url, headers=api_head)

# (4) Check response code
# print('Response Code: {}'.format(response.status_code))
# print('Response OK?: {}'.format(response.ok))

# (5) Check response body
# print('Response Body:')
# print(response.text)


# (6) text -> dict
dict_data = json.loads(response.text)

# (7)Output VM list CSV
i = 0
while i < dict_data['metadata']['total_entities']:
    vms= (
        dict_data['entities'][i]['name'], 
        dict_data['entities'][i]['description'], 
        dict_data['entities'][i]['num_cores_per_vcpu'],
        dict_data['entities'][i]['num_vcpus'],
        dict_data['entities'][i]['memory_mb'], 
        dict_data['entities'][i]['uuid']
        )
    print(*vms,sep=',')
    i += 1

Supplement

auth_str = USER + ':' + PASSWORD
auth_str = api_head = {
    'Authorization': 'Basic ' + base64.b64encode(auth_str.encode('utf-8')).decode(),
}
# (6) text -> dict
dict_data = json.loads(response.text)

# (7)Output VM list CSV
i = 0
while i < dict_data['metadata']['total_entities']:
    vms= (
        dict_data['entities'][i]['name'], 
        dict_data['entities'][i]['description'], 
        dict_data['entities'][i]['num_cores_per_vcpu'],
        dict_data['entities'][i]['num_vcpus'],
        dict_data['entities'][i]['memory_mb'], 
        dict_data['entities'][i]['uuid']
        )
    print(*vms,sep=',')
    i += 1

Execution result

PS C:\Users\oresama>  get_aos_rest.py
Move VM,RX-Autodeployed-VM,4,1,8192,ffac0fb7-6a0b-45b1-a3ea-7c8079af2364
RXAutomationPC,NutanixPrismCentral,1,4,16384,f6817073-c941-4504-8034-a1d776b03a4c
Windows 2012 VM,RX-Autodeployed-VM,4,1,8192,23647618-2d45-46ac-8909-ea1444be6d94
Windows 10 VM,RX-Autodeployed-VM,4,1,8192,59a768a1-556d-4c17-bd84-71875a666d99
AutoDC VM,RX-Autodeployed-VM,4,1,8192,68eef805-3671-4717-99d6-5a07723da365
CentOS VM,RX-Autodeployed-VM,4,1,8192,cd9d44b4-db7a-4582-91f0-44d5d27aff2b
{"metadata":{"grand_total_entities":6,"total_entities":6,"count":6,"start_index":0,"end_index":6},"entities":[{"allow_live_migrate":true,"gpus_assigned":false,"boot":{"disk_address":{"device_bus":"scsi","device_index":0},"boot_device_type":"disk"},"description":"RX-Autodeployed-VM","ha_priority":0,"memory_mb":8192,"name":"Move VM","num_cores_per_vcpu":4,"num_vcpus":1,"power_state":"off","timezone":"UTC","uuid":"ffac0fb7-6a0b-45b1-a3ea-7c8079af2364","vm_features":{"AGENT_VM":false,"VGA_CONSOLE":true},"vm_logical_timestamp":1,"machine_type":"pc"},{"allow_live_migrate":true,"gpus_assigned":false,"description":"NutanixPrismCentral","ha_priority":0,"host_uuid":"fab5dfe4-f92d-4ce8-b296-4790dd19f4c8","memory_mb":16384,"name":"RXAutomationPC","num_cores_per_vcpu":1,"num_vcpus":4,"power_state":"on","timezone":"UTC","uuid":"f6817073-c941-4504-8034-a1d776b03a4c","vm_features":{"AGENT_VM":false,"VGA_CONSOLE":true},"vm_logical_timestamp":2,"machine_type":"pc"},{"allow_live_migrate":true,"gpus_assigned":false,"boot":{"disk_address":{"device_bus":"scsi","device_index":0},"boot_device_type":"disk"},"description":"RX-Autodeployed-VM","ha_priority":0,"memory_mb":8192,"name":"Windows 2012 VM","num_cores_per_vcpu":4,"num_vcpus":1,"power_state":"off","timezone":"UTC","uuid":"23647618-2d45-46ac-8909-ea1444be6d94","vm_features":{"AGENT_VM":false,"VGA_CONSOLE":true},"vm_logical_timestamp":1,"machine_type":"pc"},{"allow_live_migrate":true,"gpus_assigned":false,"boot":{"disk_address":{"device_bus":"scsi","device_index":0},"boot_device_type":"disk"},"description":"RX-Autodeployed-VM","ha_priority":0,"host_uuid":"fee3e23a-2c0f-4a51-963e-289601935fd3","memory_mb":8192,"name":"Windows 10 VM","num_cores_per_vcpu":4,"num_vcpus":1,"power_state":"on","timezone":"UTC","uuid":"59a768a1-556d-4c17-bd84-71875a666d99","vm_features":{"AGENT_VM":false,"VGA_CONSOLE":true},"vm_logical_timestamp":2,"machine_type":"pc"},{"allow_live_migrate":true,"gpus_assigned":false,"boot":{"disk_address":{"device_bus":"scsi","device_index":0},"boot_device_type":"disk"},"description":"RX-Autodeployed-VM","ha_priority":0,"host_uuid":"fee3e23a-2c0f-4a51-963e-289601935fd3","memory_mb":8192,"name":"AutoDC VM","num_cores_per_vcpu":4,"num_vcpus":1,"power_state":"on","timezone":"UTC","uuid":"68eef805-3671-4717-99d6-5a07723da365","vm_features":{"AGENT_VM":false,"VGA_CONSOLE":true},"vm_logical_timestamp":2,"machine_type":"pc"},{"allow_live_migrate":true,"gpus_assigned":false,"boot":{"disk_address":{"device_bus":"scsi","device_index":0},"boot_device_type":"disk"},"description":"RX-Autodeployed-VM","ha_priority":0,"memory_mb":8192,"name":"CentOS VM","num_cores_per_vcpu":4,"num_vcpus":1,"power_state":"off","timezone":"UTC","uuid":"cd9d44b4-db7a-4582-91f0-44d5d27aff2b","vm_features":{"AGENT_VM":false,"VGA_CONSOLE":true},"vm_logical_timestamp":1,"machine_type":"pc"}]}

Summary

Recommended Posts

Operate Nutanix with REST API Part 2
Operate Jupyter with REST API to extract and save Python code
Cloud DevOps Cookbook Part 4-Explore DevOps DirectMail in Python with REST API
Create a REST API to operate dynamodb with the Django REST Framework
Easy REST API with API Gateway / Lambda / DynamoDB
Operate Kinesis with Python
sandbox with neo4j part 10
Extrude with Fusion360 API
Operate Blender with Python
How to operate Discord API with Python (bot registration)
Operate Excel with Python (1)
Operate Excel with Python (2)
The first API to make with python Djnago REST framework
I tried Google Sign-In with Spring Boot + Spring Security REST API
Forex automatic trading with genetic algorithm Part 3 Actual trading with Oanda API
Image download with Flickr API
Image processing with Python (Part 2)
Operate Excel with Python openpyxl
Studying Python with freeCodeCamp part1
Use Trello API with python
Bordering images with python Part 1
Operate Db2 container with Go
Operate TwitterBot with Lambda, Python
Scraping with Selenium + Python Part 1
Create an API with Django
Use Twitter API with Python
API with Flask + uWSGI + Nginx
Get information with zabbix api
[Note] Operate MongoDB with Python
Studying Python with freeCodeCamp part2
Image processing with Python (Part 1)
Web API with Python + Falcon
Operate your website with Python_Webbrowser
Solving Sudoku with Python (Part 2)
Image processing with Python (Part 3)
Play RocketChat with API / Python
Support yourself with Twitter API
Scraping with Selenium + Python Part 2
[Python] [SQLite3] Operate SQLite with Python (Basic)
Call the API with python3.
Use subsonic API with python3
ROS course 105 Operate toio with ROS
Django REST framework with Vue.js
Successful update_with_media with twitter API
Login with django rest framework
Qiita API Oauth with Django
Get ranking with Rakuten API
A story about adding a REST API to a daemon made with Python
Implementation of CRUD using REST API with Python + Django Rest framework + igGrid
Discord Bot with recording function starting with Python: (5) Directly operate the Discord API
Create REST API that returns the current time with Python3 + Falcon
Image upload & download to Azure Storage. With Python + requests + REST API
Try to create a Qiita article with REST API [Environmental preparation]
LINE BOT (Messaging API) development with API Gateway and Lambda (Python) [Part 2]