使用REST API和Python获取vCenter虚拟机的过滤列表



我需要获得一个基于通配符的VMware vCenter虚拟机列表。据我所知,vCenter不支持通配符。我无法提取VM的完整列表,因为我的环境中有一千多个VM。

还有一个类似于我的问题;如何在vmware vSphere客户端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多个虚拟机中进行分页,然后在客户端本地进行筛选。

有一件事可能值得一看,vSphere Automation SDK for Python。示例代码中的操作方式没有任何问题,但SDK是为配合vSphere的REST API服务而构建的,并且有一些示例代码可能也会在回购中帮助您。

无法通过通配符进行筛选。你可以做的是把每个主机的所有虚拟机都拉下来,然后从那里过滤,比如这样:

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']}

然后使用regex模块和/或jmespath来完成过滤器。

最新更新