How to connect to VMware APIrest using Python

90 Views Asked by At

`Need to connect to vmware apirest, My code is in python, but i have an error.

Ingrese el nombre de host del vCenter: [myIP] Ingrese el nombre de usuario para conectarse a MyIP: [user] user Ingrese la contraseña para el usuario [email protected]:

  • MyIP: Error en la autenticación o en la petición* My code:
default_vc = "MyIP"
  domain = "vsphere.local"

  import requests
  from requests.packages.urllib3.exceptions import InsecureRequestWarning
  requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL:@SECLEVEL=1'
  session = requests.Session()
  session.verify = False

  import getpass

  def get_session_info(default_vc, domain):

     default_vc = default_vc

     vc = input("Ingrese el nombre de host del vCenter: [" + default_vc + "] ")
     if not vc:
         vc = default_vc
     myuser = getpass.getuser()
     username = input("Ingrese el nombre de usuario para conectarse a " + vc + ": [" + myuser + '] '      )
      if not username:
          username = myuser
       username = username + "@" + domain
     password = getpass.getpass("Ingrese la contraseña para el usuario " + username + ": ")
     while not password:
         print("Error: Debe ingresar una contraseña")
         password = getpass.getpass("Ingrese la contraseña para el usuario " + username + ": ")
     return vc, username, password

 def get_vc_session(vc, domain, username, password):
     session.post('https://' + vc + '.' + domain + '/rest/com/vmware/cis/session', auth=(username,  password))
     return session
 
 import json

 import getpass

 def get_host(vc, domain, session):
     request_json_response = session.get('https://10.71.34.51/' + vc + '.' + domain +   'rest/vcenter/host')
     if request_json_response.status_code == 200:
         print(vc + ": Autenticación exitosa")
     else:
         print(vc + ": Error en la autenticación o en la petición")
         exit(1)
     host_list = json.loads(request_json_response.text)
     host_list_value = host_list["value"]
     return host_list_value

vc, username, password = get_session_info(default_vc, domain)
vc_session = get_vc_session(vc, domain, username, password)

host_list = get_host(vc, domain, vc_session)

for item in host_list:
    for item_key, item_value in item.items():
        print(item_key + ":", end="")
        print(str(item_value) + " ", end="\t")
    print()

I need to solve this`

1

There are 1 best solutions below

1
Saxtheowl On

There is some problems in your code, first you are not checking the response in session.post('https://' + vc + '.' + domain + '/rest/com/vmware/cis/session', auth=(username, password)) and also the ip is hardcodedhttps://10.71.34.51/ replace it with the vc parameter.

from getpass import getpass
import requests
import json

from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL:@SECLEVEL=1'

default_vc = "MyIP"
domain = "vsphere.local"
session = requests.Session()
session.verify = False

def get_session_info(default_vc, domain):

    vc = input(f"Enter the vCenter hostname: [{default_vc}] ") or default_vc
    username = input(f"Enter the username to connect to {vc}: [{getpass.getuser()}] ") or getpass.getuser()
    username = f"{username}@{domain}"
    password = getpass(f"Enter the password for user {username}: ")

    while not password:
        print("Error: You must enter a password")
        password = getpass(f"Enter the password for user {username}: ")

    return vc, username, password

def get_vc_session(vc, domain, username, password):
    url = f'https://{vc}.{domain}/rest/com/vmware/cis/session'
    response = session.post(url, auth=(username, password))
    response.raise_for_status()  # Raise an exception if the request failed
    return session

def get_host(vc, domain, session):
    url = f'https://{vc}.{domain}/rest/vcenter/host'
    response = session.get(url)

    if response.status_code == 200:
        print(f"{vc}: Successful authentication")
    else:
        print(f"{vc}: Authentication or request error")
        exit(1)

    host_list_value = response.json()["value"]
    return host_list_value

vc, username, password = get_session_info(default_vc, domain)
vc_session = get_vc_session(vc, domain, username, password)
host_list = get_host(vc, domain, vc_session)

for item in host_list:
    for item_key, item_value in item.items():
        print(f"{item_key}: {item_value}\t", end="")
    print()