簡體   English   中英

使用 REST API 和 Python 獲取經過篩選的 vCenter 虛擬機列表?

[英]Get a filtered list of vCenter VMs using the REST API and Python?

我需要獲取基於通配符的 VMware vCenter VM 列表。 據我了解,vCenter 不支持通配符。 我無法提取完整的虛擬機列表,因為我的環境中有超過一千個虛擬機。

還有一個問題與我的類似,“How do i filter using a partial VM name (string) in vmware vSphere client REST API?” 從去年開始,但答案是一個我無法理解的 C# 程序,因為我真的不知道 C#。基本上,C# 程序直接訪問 UI 中的搜索功能並提取數據(非常棒。)。 當作者開始使用 cookie 時,我在 C# 程序中迷路了。

請原諒我的代碼,我是 Python 的新手,我正在嘗試找出 API。 我是一名操作系統工程師,但我想在編程方面做得更好。 :) 這是我認為目前有效的代碼。 有一些打印語句可以在程序運行時轉儲數據,以便我可以看到 API 響應:

import json
from base64 import b64encode
import base64
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from urllib.parse import parse_qs, urlparse
from bs4 import BeautifulSoup

vcip="myvcenter.fqdn.local" # vCenter server ip address/FQDN
vcid = "testuser@testdomain" # TESTING: Username
vcpw = "SeekretPassword" # TESTING: password

def get_loginurl(vcip):
         vcurl = requests.get('https://'+vcip+'/ui/login',allow_redirects=True, verify=False)
         return vcurl.url

# Encode the username and password. 
vccred64enc = base64.urlsafe_b64encode(bytes(f'{vcid}:{vcpw}',
                                encoding='utf-8')).decode('utf-8')
# Create the authentication header
auth_header = f'Basic {vccred64enc}'
print(auth_header)
print("="*60)

# DEBUG: Display the SAML URL
vcuilogin = get_loginurl(vcip)
print(vcuilogin)
print("="*60)

# DEBUG: Authenticate to the redirected URL
saml1response = requests.post(vcuilogin,
                      headers={"Authorization": auth_header}, verify=False)
print(saml1response.url)
print("="*60)

# Castle Authorization - idk what this means
headers2 = {
      'Authorization': auth_header,
      'Content-type': 'application/x-www-form-urlencoded',
    'CastleAuthorization=': auth_header
    }

# Parse the URL and then separate the query section
samlparsed = urlparse(saml1response.url)
saml_qs_parse = parse_qs(samlparsed.query)

# Convert from a list item to a single string
samlrequest = ''.join(saml_qs_parse['SAMLRequest'])
samlparams = {'SAMLRequest': samlrequest}

buildurl1 = f"https://{samlparsed.netloc}{samlparsed.path}"

response = requests.post(buildurl1, params=samlparams, headers=headers2, verify=False)

# Make some Soup so that we can find the SAMLResponse
soup = BeautifulSoup(response.text, "html.parser")
#Extract the SAMLResponse value
saml_respvalue = soup.find('input', {'name': 'SAMLResponse'})['value']

print(f'SAMLResponse: {saml_respvalue}')

長話短說,vSphere REST API 並不是真的用於服務器端搜索。 但是,有一個分頁功能可以讓您分頁瀏覽您擁有的 1000 多個虛擬機,然后在客戶端本地過濾它們。

一件事可能值得研究,用於 Python 的 vSphere Automation SDK。 您在示例代碼中執行此操作的方式沒有任何問題,但SDK是為與 REST API 服務一起使用而構建的

不能按通配符過濾。 您可以做的是拉下每個主機的所有 VM 並從那里進行過濾,如下所示:

import requests
import json

vcenter_host = 'https://vcenter.example.com'
session = requests.Session()
session.post(f"{vcenter_host}/rest/com/vmware/cis/session",
             auth=(username, password), verify=False)

# Reasonable assumption you have less that 1000 hosts
hosts =json.loads(session.get(f"{vcenter_host}/rest/vcenter/hosts").text)

vms = {i['host']: session.get(f"{vcenter_host}/rest/vcenter/vm",
                             params={'filter.hosts': i['host']})
      for i in hosts['value']}

然后使用正則表達式模塊和/或 jmespath 來完成你的過濾器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM