Vsphere接口調研

參考項目:https://github.com/vmware/pyvmomi-community-samples
參考鏈接:https://code.vmware.com/web/dp/explorer-apis?id=197

準備開發(fā)環(huán)境

1. Installed python
2. Installed pip
3. Install pyvmomi using pip
$ pip install pyvmomi

現在已經可以使用vsphere提供的api棘幸,進行基本的操作了。

# 創(chuàng)建虛擬機流程

1. 跨過認證
from pyVim import connect
import atexit

#獲取連接對象
si = connect.SmartConnectNoSSL(host=args.host,
                             user=args.user,
                             pwd=args.password,
                             port=int(args.port))

#斷開連接
atexit.register(connect.Disconnect, si)
2. 創(chuàng)建虛擬機(只包含內存,cpu,網卡)
from pyVmomi import vim
from tools import tasks

def get_obj(content, vimtype, name):
    obj = None
    container = content.viewManager.CreateContainerView(
        content.rootFolder, vimtype, True)
    for c in container.view:
        if c.name == name:
            obj = c
            break
    return obj

#添加網卡配置
def add_nic_spec(si, config_spec, network):
    nic_changes = []

    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    nic_spec.device = vim.vm.device.VirtualE1000()
    nic_spec.device.deviceInfo = vim.Description()
    nic_spec.device.deviceInfo.summary = 'vCenter API test'
    nic_spec.device.backing = \
        vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
    nic_spec.device.backing.useAutoDetect = False
    content = si.RetrieveContent()
    nic_spec.device.backing.network = get_obj(content, [vim.Network], network)
    nic_spec.device.backing.deviceName = network
    nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.allowGuestControl = True
    nic_spec.device.connectable.connected = True
    nic_spec.device.connectable.status = 'untried'
    nic_spec.device.wakeOnLanEnabled = True
    nic_spec.device.addressType = 'generated'
    nic_changes.append(nic_spec)
    config_spec.deviceChange = nic_changes

    return config_spec

def create_dummy_vm(name, si, vm_folder, resource_pool, datastore):
    #定義vm存儲目錄
    datastore_path = '[' + datastore + '] ' + vm_name

    # bare minimum VM shell, no disks. Feel free to edit
    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)
    #配置vm boot配置
    config = vim.vm.ConfigSpec(name=name, memoryMB=1048, numCPUs=1, files=vmx_file, guestId='centos7_64Guest',
                               version='vmx-13')
    config = add_nic_spec(si, config, network='Ceph_Net')

    #創(chuàng)建虛擬機
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    tasks.wait_for_tasks(si, [task])

content = si.RetrieveContent()
datacenter = content.rootFolder.childEntity[0]
vmfolder = datacenter.vmFolder
hosts = datacenter.hostFolder.childEntity
resource_pool = hosts[0].resourcePool

name = "test_vm02" 
create_dummy_vm(name, service_instance, vmfolder, resource_pool,
                        args.datastore)
3. 掛載磁盤到虛擬機
from pyVmomi import vim
from tools import tasks
from pyVim.task import WaitForTask

def get_obj(content, vimtype, name):
    obj = None
    container = content.viewManager.CreateContainerView(
        content.rootFolder, vimtype, True)
    for c in container.view:
        if c.name == name:
            obj = c
            break
    return obj

def add_scsi_device_to_vm(vm):
    """
    add scsi device to a virtual machine
    :param vm: virtual machine object
    :return: scsi configuration
    :TBD
    """
    spec = vim.vm.ConfigSpec()
    scsi_ctr = vim.vm.device.VirtualDeviceSpec()
    scsi_ctr.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    scsi_ctr.device = vim.vm.device.VirtualLsiLogicController()
    scsi_ctr.device.deviceInfo = vim.Description()
    scsi_ctr.device.unitNumber = 3
    scsi_ctr.device.busNumber = 0
    scsi_ctr.device.hotAddRemove = True
    scsi_ctr.device.sharedBus = 'noSharing'
    scsi_ctr.device.scsiCtlrUnitNumber = 7
    spec.deviceChange = [scsi_ctr]

    LOGGER.info("SCSI device added to %s", vm.config.name)
    return scsi_ctr

def add_disk(vm, si, disk_size, disk_type):
    spec = vim.vm.ConfigSpec()
    scsi_ctr = add_scsi_device_to_vm(vm)
    controller = scsi_ctr.device
    # get all disks on a VM, set unit_number to the next available
    unit_number = 0
    for dev in vm.config.hardware.device:
        if hasattr(dev.backing, 'fileName'):
            unit_number = int(dev.unitNumber) + 1
            # unit_number 7 reserved for scsi controller
            if unit_number == 7:
                unit_number += 1
            if unit_number >= 16:
                print "we don't support this many disks"
                return
        if isinstance(dev, vim.vm.device.VirtualSCSIController):
            controller = dev
    # add disk here
    dev_changes = []
    new_disk_kb = int(disk_size) * 1024 * 1024
    disk_spec = vim.vm.device.VirtualDeviceSpec()
    disk_spec.fileOperation = "create"
    disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    disk_spec.device = vim.vm.device.VirtualDisk()
    disk_spec.device.backing = \
        vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
    if disk_type == 'thin':
        disk_spec.device.backing.thinProvisioned = True
    disk_spec.device.backing.diskMode = 'persistent'
    disk_spec.device.unitNumber = unit_number
    disk_spec.device.capacityInKB = new_disk_kb
    disk_spec.device.controllerKey = controller.key
    dev_changes.append(disk_spec)
    spec.deviceChange = dev_changes
    task = vm.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])

#通過vm uuid過濾虛擬機
search_index = si.content.searchIndex
vm = search_index.FindByUuid(None, args.uuid, True, True)
#掛載磁盤(磁盤大小單位GB,類型可選項:thin,thick)
# thin:虛擬硬盤實際大小隨著使用量而浮動,直到使用到硬盤分配上限
# thick:創(chuàng)建虛擬硬盤是一次性分配完全
add_disk(vm, si, args.disk_size, args.disk_type)
4. 掛載CD_ROM到虛擬機
#判斷vm是否已經掛載CD-Rom
def check_vm_cdrom(vm):
    for device in vm.config.hardware.device:
        if isinstance(device, vim.vm.device.VirtualCdrom):
            return device
    return None

#查找設備控制器
def find_free_ide_controller(vm):
    for dev in vm.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualIDEController):
            # If there are less than 2 devices attached, we can use it.
            if len(dev.device) < 2:
                return dev
    return None

#生成CD-Rom配置
def new_cdrom_spec(controller_key, backing):
    connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    connectable.allowGuestControl = True
    connectable.startConnected = True

    cdrom = vim.vm.device.VirtualCdrom()
    cdrom.controllerKey = controller_key
    cdrom.key = -1
    cdrom.connectable = connectable
    cdrom.backing = backing
    return cdrom

search_index = si.content.searchIndex
#獲取vm_obj昙衅,需要傳入參數vm_uuid
vm = search_index.FindByUuid(None, uuid, True ,True)

if vm is None:
    raise Exception('Failed to find VM %s in datacenter %s' %
                    (dc.name, args.name))
controller = find_free_ide_controller(vm)
if controller is None:
    raise Exception('Failed to find a free slot on the IDE controller')

cdrom = check_vm_cdrom(vm)
op = vim.vm.device.VirtualDeviceSpec.Operation
iso = args.iso
if iso is not None:
    deviceSpec = vim.vm.device.VirtualDeviceSpec()
    if cdrom is None:  # add a cdrom
        print("Adding a new cd-Rom......")
        backing = vim.vm.device.VirtualCdrom.IsoBackingInfo(fileName=iso)
        cdrom = new_cdrom_spec(controller.key, backing)
        deviceSpec.operation = op.add
    else:  # edit an existing cdrom
        print("Updating a old cd-Rom......")
        backing = vim.vm.device.VirtualCdrom.IsoBackingInfo(fileName=iso)
        cdrom.backing = backing
        deviceSpec.operation = op.edit
    deviceSpec.device = cdrom
    configSpec = vim.vm.ConfigSpec(deviceChange=[deviceSpec])
    WaitForTask(vm.Reconfigure(configSpec))

    cdroms = find_device(vm, vim.vm.device.VirtualCdrom)
    cdrom = filter(lambda x: type(x.backing) == type(backing) and
                       x.backing.fileName == iso, cdroms)[0]
else:
    print('Skipping ISO test as no iso provided.')

# 獲取虛擬機列表及詳情

from pyVmomi import vim

#打印虛擬機詳情
def print_vm_info(virtual_machine):
    """
    Print information for a particular virtual machine or recurse into a
    folder with depth protection
    """
    summary = virtual_machine.summary
    print("Name       : ", summary.config.name)
    print("Template   : ", summary.config.template)
    print("Path       : ", summary.config.vmPathName)
    print("Guest      : ", summary.config.guestFullName)
    print("Instance UUID : ", summary.config.instanceUuid)
    print("Bios UUID     : ", summary.config.uuid)
    annotation = summary.config.annotation
    if annotation:
        print("Annotation : ", annotation)
    print("State      : ", summary.runtime.powerState)
    if summary.guest is not None:
        ip_address = summary.guest.ipAddress
        tools_version = summary.guest.toolsStatus
        if tools_version is not None:
            print("VMware-tools: ", tools_version)
        else:
            print("Vmware-tools: None")
        if ip_address:
            print("IP         : ", ip_address)
        else:
            print("IP         : None")
    if summary.runtime.question is not None:
        print("Question  : ", summary.runtime.question.text)
    print("")

#獲取所有虛擬機對象
content = si.RetrieveContent()
container = content.rootFolder  # starting point to look into
viewType = [vim.VirtualMachine]  # object types to look for
recursive = True  # whether we should look into it recursively
containerView = content.viewManager.CreateContainerView(container, viewType, recursive)

#遍歷虛擬機列表打印虛擬機詳情
children = containerView.view
for child in children:
    print_vm_info(child)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末愁憔,一起剝皮案震驚了整個濱河市抹锄,隨后出現的幾起案子焰手,更是在濱河造成了極大的恐慌糟描,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件书妻,死亡現場離奇詭異船响,居然都是意外死亡,警方通過查閱死者的電腦和手機躲履,發(fā)現死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進店門见间,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人工猜,你說我怎么就攤上這事米诉。” “怎么了篷帅?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵史侣,是天一觀的道長。 經常有香客問我魏身,道長惊橱,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任箭昵,我火速辦了婚禮税朴,結果婚禮上,老公的妹妹穿的比我還像新娘家制。我一直安慰自己正林,他們只是感情好,可當我...
    茶點故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布颤殴。 她就那樣靜靜地躺著觅廓,像睡著了一般。 火紅的嫁衣襯著肌膚如雪诅病。 梳的紋絲不亂的頭發(fā)上哪亿,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天,我揣著相機與錄音贤笆,去河邊找鬼蝇棉。 笑死,一個胖子當著我的面吹牛芥永,可吹牛的內容都是我干的篡殷。 我是一名探鬼主播,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼埋涧,長吁一口氣:“原來是場噩夢啊……” “哼板辽!你這毒婦竟也來了奇瘦?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤劲弦,失蹤者是張志新(化名)和其女友劉穎耳标,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體邑跪,經...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡次坡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了画畅。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片砸琅。...
    茶點故事閱讀 38,724評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖轴踱,靈堂內的尸體忽然破棺而出症脂,到底是詐尸還是另有隱情,我是刑警寧澤淫僻,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布诱篷,位于F島的核電站,受9級特大地震影響嘁傀,放射性物質發(fā)生泄漏兴蒸。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一细办、第九天 我趴在偏房一處隱蔽的房頂上張望橙凳。 院中可真熱鬧,春花似錦笑撞、人聲如沸岛啸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽坚踩。三九已至,卻和暖如春瓤狐,著一層夾襖步出監(jiān)牢的瞬間瞬铸,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工础锐, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留嗓节,地道東北人。 一個月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓皆警,卻偏偏與公主長得像拦宣,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,627評論 2 350