Skip to content

Instantly share code, notes, and snippets.

@sky-joker sky-joker/
Last active Jul 18, 2017

What would you like to do?
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim, vmodl
import ssl
import atexit
# 接続先情報
host = 'ESXi or vCenter IP'
username = 'username'
password = 'password'
# クローン情報
clone_target_vm = 'クローン元VM名'
target_host = '展開先ESXiホスト名'
new_vm_name = '新しいVM名'
def get_mob_info(content, mob, target=''):
Management Objectを取得する。
:type content: vim.ServiceInstanceContent
:param content: ServiceContent(
:type mob: Management Object
:param mob: 取得する対象のManagement Objectを指定
:type target: str
:param target: 返すmobの名前を指定
:rtype: Management Object
:return: 指定したManagement Object又はContainerViewを返す
r = content.viewManager.CreateContainerView(content.rootFolder,
# 返すmobを名前で指定する場合
for i in r.view:
if( == target):
r = i
return r
def main():
# SSL証明書対策
context = None
if hasattr(ssl, '_create_unverified_context'):
context = ssl._create_unverified_context()
# 接続
si = SmartConnect(host = host,
user = username,
pwd = password,
sslContext = context)
# 処理完了時にvCenterから切断
atexit.register(Disconnect, si)
# ServiceContent(Data Object)を取得
content = si.content
# RelocateSpecを作成
relocate_spec = vim.vm.RelocateSpec() = get_mob_info(content, vim.HostSystem, target_host)
# CloneSpec作成
clone_spec = vim.vm.CloneSpec()
clone_spec.location = relocate_spec
clone_spec.powerOn = False
clone_spec.template = False
# Clone実行
target_vm = get_mob_info(content, vim.VirtualMachine, clone_target_vm)
target_vm.CloneVM_Task(folder = target_vm.parent, name = new_vm_name, spec = clone_spec)
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.