Python で vSphere を操作できるようにする。(pyvmomi)

Python で vSphere を操作できるようにする。(pyvmomi)

Oracle Linux 7 から、Python で vSphere を操作できるようにしてみようと思います。

※いわゆる Red Hat 系ディストリビューションなので RHEL 7.x や CentOS 7.x なども同様です。

pyvmomi という Python のライブラリを使用します。

これは、VMware の GitHub サイトにあります。

vmware/pyvmomi

https://github.com/vmware/pyvmomi

PyPI にも登録されているので、今回は pip コマンドでインストールします。

PyPI - the Python Package Index

pyvmomi

https://pypi.python.org/pypi/pyvmomi/6.0.0.2016.4

今回の環境。

Oracle Linux 7.2 にインストールします。

[root@vm01 ~]# cat /etc/oracle-release

Oracle Linux Server release 7.2

Python のバージョンはこれです。

[root@vm01 ~]# python -V

Python 2.7.5

接続先は、vCenter Server Applicance 6.0 u1 です。

pyvmomi のインストール。

Oracle Linux 7.x は、デフォルトではパッケージがほとんどインストールされていないので、

今回は開発ツール(Development Tools)をグループインストールしてしまいます。

[root@vm01 ~]# yum groupinstall -y "Development Tools"

easy_install が含まれる python-setuptools をインストールします。

[root@vm01 ~]# yum install -y python-setuptools

pip をインストールします。

[root@vm01 ~]# easy_install pip

pip で、pyvmomi をインストールします。

[root@vm01 ~]# pip install pyvmomi

pyvmomi がインストールされました。

[root@vm01 ~]# pip freeze

backports.ssl-match-hostname==3.4.0.2

configobj==4.7.2

decorator==3.4.0

ethtool==0.8

iniparse==0.4

M2Crypto==0.21.1

pciutils==1.7.3

perf==0.1

pycurl==7.19.0

pygobject==3.14.0

pygpgme==0.3

pyliblzma==0.5.3

pyOpenSSL==0.13.1

python-dmidecode==3.10.13

pyudev==0.15

pyvmomi==6.0.0.2016.4

pyxattr==0.5.1

requests==2.10.0

rhnlib==2.5.65

six==1.10.0

slip==0.4.0

slip.dbus==0.4.0

urlgrabber==3.10

yum-metadata-parser==1.1.4

サンプルスクリプトのインストール。

サンプルスクリプトも VMware の GitHub サイトにあるので、git clone します。

[root@vm01 ~]# git clone https://github.com/vmware/pyvmomi-community-samples

下記のようなサンプルファイルが配置されます。

[root@vm01 ~]# cd pyvmomi-community-samples/samples/

[root@vm01 samples]# ls -1

README.md

__init__.py

add_disk_to_vm.py

add_vm_extra_config_tags.py

change_disk_mode.py

change_vm_cd_backend.py

change_vm_nic_state.py

change_vm_vif.py

clone_vm.py

create_folder_in_datacenter.py

create_random_marvel_vms.py

create_snapshot.py

delete_disk_from_vm.py

deploy_ovf.py

destroy_vm.py

esxi_perf_sample.py

execute_program_in_vm.py

export_vm.py

find_by_uuid.py

generate_html5_console.py

getallvms.py

getorphanedvms.py

getvnicinfo.py

hello_world_vcenter.py

hello_world_vcenter_with_yaml_recorder.py

list_datastore_cluster.py

list_datastore_info.py

list_dc_datastore_info.py

list_host_alarms.py

list_vmwaretools_status.py

make_dc_and_cluster.py

pyvmomi-to-suds.py

reboot_vm.py

reconfigure_host_for_ha.py

renamer.py

sessions_list.py

set_note.py

set_vcenter_motd.py

soft_reboot.py

suds-to-pyvmomi.py

tests

tools

upload_file_to_datastore.py

upload_file_to_vm.py

vSphereAutoRestartManager.py

vcenter_details.py

virtual_machine_device_info.py

virtual_machine_power_cycle_and_question.py

vminfo_quick.py

waitforupdates.py

動作確認。

ためしにサンプルスクリプト「hello_world_vcenter.py」で、vCenter(192.168.5.75)に接続してみます。

このスクリプトの使用方法です。

[root@vm01 samples]# python hello_world_vcenter.py --help

usage: hello_world_vcenter.py [-h] -s HOST [-o PORT] -u USER [-p PASSWORD]

Standard Arguments for talking to vCenter

optional arguments:

  -h, --help            show this help message and exit

  -s HOST, --host HOST  vSphere service to connect to

  -o PORT, --port PORT  Port to connect on

  -u USER, --user USER  User name to use when connecting to host

  -p PASSWORD, --password PASSWORD

                        Password to use when connecting to host

接続できました。

[root@vm01 samples]# python hello_world_vcenter.py -s 192.168.5.75 -u administrator@vsphere.local -p 'パスワード'

Hello World!

If you got here, you authenticted into vCenter.

The server is 192.168.5.75!

current session id: 52fa04cc-85ad-e576-3925-6d7f11776e22

Well done!

Download, learn and contribute back:

https://github.com/vmware/pyvmomi-community-samples

[root@vm01 samples]#

vCenter の証明書を入れ替えていない場合は、SSL 証明書エラーを回避するため

下記のように3行ほどサンプル スクリプト hello_world_vcenter.py を修正する必要があります。

[gowatana@client01 samples]$ git diff

diff --git a/samples/hello_world_vcenter.py b/samples/hello_world_vcenter.py

index 1320d05..1260538 100755

--- a/samples/hello_world_vcenter.py

+++ b/samples/hello_world_vcenter.py

@@ -22,6 +22,7 @@ a friendly encouragement to joining the community!

import atexit

import argparse

import getpass

+import ssl

from pyVim import connect

from pyVmomi import vmodl

@@ -76,7 +77,8 @@ def main():

         service_instance = connect.SmartConnect(host=args.host,

                                                 user=args.user,

                                                 pwd=args.password,

-                                                port=int(args.port))

+                                                port=int(args.port),

+                                                sslContext=ssl._create_unverified_context())

         atexit.register(connect.Disconnect, service_instance)

[gowatana@client01 samples]$

ためしに、対話モードの Python で ESXi (HostSystem)の情報を取得してみました。

[root@vm01 samples]# python

Python 2.7.5 (default, Nov 21 2015, 00:39:04)

[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> from pyVim import connect

>>> from pyVmomi import vim

>>> si = connect.SmartConnect(host='192.168.5.75',user='administrator@vsphere.local',pwd='パスワード')

>>> content = si.RetrieveContent()

>>> host_view = content.viewManager.CreateContainerView(content.rootFolder,[vim.HostSystem],True)

>>> for h in host_view.view:

...   print 'HostName:', h.name

...   print 'Hardware:', h.hardware.systemInfo.vendor, h.hardware.systemInfo.model

...   print 'Version: ', h.summary.config.product.version, h.summary.config.product.build

...   print '---'

...

HostName: hv-h01.godc.lab

Hardware: HP ProLiant Micro Server

Version : 6.0.0 3029758

---

HostName: hv-d02.godc.lab

Hardware: Dell Inc. OptiPlex 9010

Version : 6.0.0 3073146

---

HostName: hv-d01.godc.lab

Hardware: Dell Inc. OptiPlex 780

Version : 6.0.0 3073146

---

HostName: hv-i01.godc.lab

Hardware: To Be Filled By O.E.M.

Version : 6.0.0 3247720

---

>>> quit()

[root@vm01 samples]#

vCenter の証明書を入れ替えていない場合は、

エラー回避のため SSL 証明書を確認しないように工夫が必要です。

[gowatana@client01 samples]$ python

Python 2.7.5 (default, May 29 2017, 20:42:36)

[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> from pyVim import connect

>>> from pyVmomi import vim

>>> import ssl

>>> si = connect.SmartConnect(host='vCenterのアドレス',user='ユーザ',pwd='パスワード',sslContext=ssl._create_unverified_context())

>>> content = si.RetrieveContent()

>>> host_view = content.viewManager.CreateContainerView(content.rootFolder,[vim.HostSystem],True)

>>> for h in host_view.view:

...   print 'HostName:', h.name

...   print 'Hardware:', h.hardware.systemInfo.vendor, h.hardware.systemInfo.model

...   print 'Version: ', h.summary.config.product.version, h.summary.config.product.build

...   print '---'

...

HostName: hv-d02.go-lab.jp

Hardware: Dell Inc. OptiPlex 9010

Version:  6.0.0 4192238

---

HostName: hv-d01.go-lab.jp

Hardware: Dell Inc. OptiPlex 3050

Version:  6.5.0 7388607

---

(省略)

>>> quit()

[gowatana@client01 samples]$

このように Python から vSphere にアクセスすることができます。

ちなみに、VMOMI は VMware Managed Object Management Interface の略のようなので、

pyvmomi は Python の VMOMI ということなのでしょう。

VMware API Related Acronyms

http://www.virtuallyghetto.com/2010/08/vmware-api-related-acronyms.html

以上、pyvmomi で vCenter に接続してみる話でした。

Comments

いまさらながら、SSL証明書エラー回避について追記しました。

Version history
Revision #:
1 of 1
Last update:
‎05-08-2016 03:42 PM
Updated by: