iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >初探oVirt-体验sdk-python
  • 315
分享到

初探oVirt-体验sdk-python

oVirtsdkpython 2023-01-31 05:01:17 315人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

日期:2015/10/20 - 2015/12/8 time 16:09主机:n86目的:初探oVirt-体验sdk-python操作内容: 一、说明 使用sdk-Python 通过pip安装 ovirt-engine-sdk-python

日期:2015/10/20 - 2015/12/8 time 16:09

主机:n86

目的:初探oVirt-体验sdk-python

操作内容:


一、说明
使用sdk-Python
通过pip安装 ovirt-engine-sdk-python
# pip install ovirt-engine-sdk-python

注:本文是从ovirt-engine-sdk-python的3.5.4更新到3.6.0.3,关于版本的差异有一个主要区别是新增了这个选项:
use_cloud_init=True

二、示例
[root@n86 bin]# cat ovirt_sdk.py 
#!/bin/env python
# -*- coding:utf-8 -*-
# for ovirt-engine-sdk-python-3.6.0.3
# 2015/12/8

from __future__ import print_function
from time import sleep

from ovirtsdk.api import API
from ovirtsdk.xml import params

__version__ = '0.2.8'

OE_URL = 'https://e01.test/api'
OE_USERNAME = 'admin@internal'
OE_PASSWord = 'TestVM'
# curl -k Https://e01.test/ca.crt -o ca.crt
OE_CA_FILE = 'ca.crt'  # ca.crt 在当前目录下


def vm_list(oe_api):
    """
        List VM
    """
    try:
        print('[I] List vms: ')
        for vm_online in oe_api.vms.list():
            print('{0}'.fORMat(vm_online.name))
    except Exception as err:
        print('[E] List VM: {0}'.format(str(err)))


def vm_start(oe_api, vm_name):
    """
        start vm by name
    """
    try:
        if vm_name not in [vm_online.name for vm_online in oe_api.vms.list()]:
            print("[E] VM not found: {0}".format(vm_name))
            return 1
        if oe_api.vms.get(vm_name).status.state != 'up':
            print('[I] Starting VM.')
            oe_api.vms.get(vm_name).start()
            print('[I] Waiting for VM to reach Up status... ', end='')
            while oe_api.vms.get(vm_name).status.state != 'up':
                print('.', end='')
                sleep(1)
            print('VM {0} is up!'.format(vm_name))
        else:
            print('[E] VM already up.')
    except Exception as err:
        print('[E] Failed to Start VM: {0}'.format(str(err)))


def vm_stop(oe_api, vm_name):
    """
        stop vm by name
    """
    try:
        if vm_name not in [vm_online.name for vm_online in oe_api.vms.list()]:
            print("[E] VM not found: {0}".format(vm_name))
            return 1
        if oe_api.vms.get(vm_name).status.state != 'down':
            print('[I] Stop VM.')
            oe_api.vms.get(vm_name).stop()
            print('[I] Waiting for VM to reach Down status... ', end='')
            while oe_api.vms.get(vm_name).status.state != 'down':
                print('.', end='')
                sleep(1)
            print('VM {0} is down!'.format(vm_name))
        else:
            print('[E] VM already down: {0}'.format(vm_name))
    except Exception as err:
        print('[E] Stop VM: {0}'.format(str(err)))


def vm_delete(oe_api, vm_name):
    """
        delete vm by name
    """
    try:
        if vm_name not in [vm_online.name for vm_online in oe_api.vms.list()]:
            print("[E] VM not found: {0}".format(vm_name))
            return 1
        oe_api.vms.get(vm_name).delete()
        print('[I] Waiting for VM to be deleted... ', end='')
        while vm_name in [vm_online.name for vm_online in oe_api.vms.list()]:
            print('.', end='')
            sleep(1)
        print('VM was removed successfully.')
    except Exception as err:
        print('[E] Failed to remove VM: {0}'.format(str(err)))


def vm_run_once(oe_api, vm_name, vm_password, vm_nic_info):
    """
        vm run once with cloud-init
    """
    try:
        if vm_name not in [vm_online.name for vm_online in oe_api.vms.list()]:
            print("[E] VM not found: {0}".format(vm_name))
            return 1
        elif vm_nic_info is None:
            print('[E] VM nic info is needed: "name_of_nic, ip_address, net_mask, gateway"')
            return 2
        elif oe_api.vms.get(vm_name).status.state == 'down':
            print('[I] Starting VM with cloud-init.')
            p_host = params.Host(address="{0}".format(vm_name))
            p_users = params.Users(user=[params.User(user_name="root", 
                                                     password=vm_password)])
            vm_nic = [nic for nic in vm_nic_info.split(', ')]
            if len(vm_nic) != 4:
                print('[E] VM nic info need 4 args: "name_of_nic, ip_address, net_mask, gateway"')
                return 3
            p_nic = params.Nics(nic=[params.NIC(name=vm_nic[0],
                                                boot_protocol="STATIC",
                                                on_boot=True,
                                                network=params.network(ip=params.IP(address=vm_nic[1],
                                                                                    netmask=vm_nic[2],
                                                                                    gateway=vm_nic[3])))])
            p_network = params.NetworkConfiguration(nics=p_nic)
            p_cloud_init = params.CloudInit(host=p_host,
                                            users=p_users,
                                            regenerate_ssh_keys=True,
                                            network_configuration=p_network)
            p_initialization = params.Initialization(cloud_init=p_cloud_init)
            vm_params = params.VM(initialization=p_initialization)
            vm_action = params.Action(vm=vm_params, use_cloud_init=True)
            oe_api.vms.get(vm_name).start(vm_action)
            
            print('[I] Waiting for VM to reach Up status... ', end='')
            while oe_api.vms.get(vm_name).status.state != 'up':
                print('.', end='')
                sleep(1)
            print('VM {0} is up!'.format(vm_name))
        else:
            print('[E] VM already up.')
            
    except Exception as err:
        print('[E] Failed to Start VM with cloud-init: {0}'.format(str(err)))


def vm_create_from_tpl(oe_api, vm_name, tpl_name, cluster_name):
    """
        create vm from template.
        notice: not (Clone/Independent), but (Thin/Dependent)
    """
    try:
        vm_params = params.VM(name=vm_name, 
                              template=oe_api.templates.get(tpl_name),
                              cluster=oe_api.clusters.get(cluster_name))
        oe_api.vms.add(vm_params)
        print('[I] VM was created from Template successfully.\nWaiting for VM to reach Down status... ', end='')
        while oe_api.vms.get(vm_name).status.state != 'down':
            print('.', end='')
            sleep(1)
        print('VM {0} is down!'.format(vm_name))
    except Exception as err:
        print('[E] Failed to create VM from template: {0}'.format(str(err)))


if __name__ == '__main__':
    import optparse
    p = optparse.OptionParser()
    p.add_option("-a", "--action", action="store", type="string", dest="action",
                 help="list|init|start|stop|delete|create[-list]")
    p.add_option("-n", "--vm-name", action="store", type="string", dest="vm_name",
                 help="provide the name of vm. eg: -a create -n vm01")
    p.add_option("-c", "--vm-cluster", action="store", type="string", dest="vm_cluster",
                 help="provide cluster name")
    p.add_option("-t", "--vm-template", action="store", type="string", dest="vm_template",
                 help="provide template name. eg: -a create -n vm01 -t tpl01 -c cluster01")
    p.add_option("-p", "--vm-password", action="store", type="string", dest="vm_password",
                 help="-a init -p password_of_vm -i vm_nic_info")
    p.add_option("-i", "--vm-nic-info", action="store", type="string", dest="vm_nic_info",
                 help='nic info: "name_of_nic, ip_address, net_mask, gateway". '
                      'eg: -a init -n vm01 -p 123456 -i "eth0, 10.0.100.101, 255.255.255.0, 10.0.100.1"')
    p.add_option("-L", "--vm-list", action="store", type="string", dest="vm_list",
                 help='a list of vms. eg: -a stop-list -L "vm01, vm02, vm03"')
    p.set_defaults(action='list',
                   vm_cluster='C01',
                   vm_template='tpl-m1')
    opt, args = p.parse_args()
    oe_conn = None
    try:
        oe_conn = API(url=OE_URL, username=OE_USERNAME, password=OE_PASSWORD, ca_file=OE_CA_FILE)
        if opt.action == 'list':
            vm_list(oe_conn)
        elif opt.action == 'start':
            vm_start(oe_conn, opt.vm_name)
        elif opt.action == 'stop':
            vm_stop(oe_conn, opt.vm_name)
        elif opt.action == 'delete':
            vm_delete(oe_conn, opt.vm_name)
        elif opt.action == 'create':
            vm_create_from_tpl(oe_conn, opt.vm_name, opt.vm_template, opt.vm_cluster)
        elif opt.action == 'init':
            vm_run_once(oe_conn, opt.vm_name, opt.vm_password, opt.vm_nic_info)
        elif opt.action == 'start-list':
            for vm in opt.vm_list.replace(' ', '').split(','):
                print('[I] try to start vm: {0}'.format(vm))
                vm_start(oe_conn, vm)
        elif opt.action == 'stop-list':
            for vm in opt.vm_list.replace(' ', '').split(','):
                print('[I] try to stop vm: {0}'.format(vm))
                vm_stop(oe_conn, vm)
        elif opt.action == 'delete-list':
            for vm in opt.vm_list.replace(' ', '').split(','):
                print('[I] try to delete: {0}'.format(vm))
                vm_delete(oe_conn, vm)
        elif opt.action == 'create-list':
            for vm in opt.vm_list.replace(' ', '').split(','):
                print('[I] try to create: {0}'.format(vm))
                vm_create_from_tpl(oe_conn, vm, opt.vm_template, opt.vm_cluster)
    except Exception as e:
        print('[E] Failed to init API: {0}'.format(str(e)))
    finally:
        if oe_conn is not None:
            oe_conn.disconnect()






ZYXW、参考
1、docs
http://www.ovirt.org/Python-sdk
http://www.ovirt.org/Testing/PythonApi
http://www.ovirt.org/Features/Cloud-Init_Integration
https://access.redhat.com/documentation/zh-CN/Red_Hat_Enterprise_Virtualization/3.5/html-single/Technical_Guide/index.html#chap-REST_API_Quick_Start_Example


--结束END--

本文标题: 初探oVirt-体验sdk-python

本文链接: https://www.lsjlt.com/news/188778.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 初探oVirt-体验sdk-python
    日期:2015/10/20 - 2015/12/8 time 16:09主机:n86目的:初探oVirt-体验sdk-python操作内容: 一、说明 使用sdk-python 通过pip安装 ovirt-engine-sdk-python...
    99+
    2023-01-31
    oVirt sdk python
  • Python 初体验
    广告:欢迎大家到 路飞学城 学习 Python~ 很喜欢 Python “薪”时代 这个词~所以我们要拥抱 “人工智能”~拥抱 “Python~” 前提:下载 Python,如果是 Mac 电脑会自带 Python。 Hello Worl...
    99+
    2023-01-31
    初体验 Python
  • JetBrainsFleet初体验
    几天前获得了fleet的体验资格。长话短说,今天就来和你一起看看现在的fleet都有啥 先看名字–fleet 什么是fleet? n. 舰队;捕鱼船队;(一国的)全部军舰,海军 看来...
    99+
    2024-04-02
  • IronPython初体验
    介绍 在 C# 程序中嵌入 IronPython 得到了很好的支持。在本教程中,我们将展示如何完成这个项目。 首先,我们将展示两个非常基本的例子,说明如何执行一个不导入任何模块的非常简单的脚本。然后,再展示如何执行使用模块的脚本。 在 C...
    99+
    2023-01-30
    初体验 IronPython
  • Egret3D之初体验
    Ⅰ,Egret3D官方文档 : https://developer.egret.com/cn/docs/3d/docs/guide/getting-started-introduction/ Ⅱ,安装3D编辑器(以前叫paper , 现在...
    99+
    2023-01-31
    之初 Egret3D
  • Service Mesh 初体验
    前言计算机软件技术发展到现在,软件架构的演进无不朝着让开发者能够更加轻松快捷地构建大型复杂应用的方向发展。容器技术最初是为了解决运行环境的不一致问题而产生的,随着不断地发展,围绕容器技术衍生出来越来越多的新方向。最近几年,云计算领域不断地出...
    99+
    2023-06-05
  • Python 初探
     按照计划,今年要学习一门面向对象的语言,学习的范围锁定几门,PHP/PERL/PYTHON/RUBY,由于上半年学了bash,感觉python比较适合自己。从今天开始不定期的出一些笔记出来 #! /usr/bin/python   ID...
    99+
    2023-01-31
    Python
  • springcloud初体验(真香)
    一、微服务简介 Ⅰ、我对微服务的理解 微服务是软件开发的一种架构方式,由单一的应用小程序构成的小服务;一个软件系统由多个服务组成;在微服务中,服务是细粒度的,协议是轻量级的(部...
    99+
    2024-04-02
  • 1、python-初探
    语言包括编译型语言和解释型语言编译型:全部翻译,再执行;c、c++解释型:边执行边翻译;python、php、java、c#、perl、ruby、javascript 一、系统位数32位系统内存的最大寻址空间位2**32,4GB64位系统...
    99+
    2023-01-31
    python
  • python unittest初探
    待测试的类:class Request:    url = ""    method = ""    paras = {}    def __init__(self,url):        self.url = url        se...
    99+
    2023-01-31
    python unittest
  • Oracle 18c安装初体验
    Oracle 18c在万众期待下终于开放下载了,目前提供Linux x86-64、Solaris(SPARC)、Solaris(x86-64)三个平台的下载: 安装包也是水涨船高,Linux版...
    99+
    2024-04-02
  • Java开发 - Redis初体验
    前言 es我们已经在前文中有所了解,和es有相似功能的是Redis,他们都不是纯粹的数据库。两者使用场景也是存在一定的差异的,本文目的并不重点说明他们之间的差异,但会简要说明,重点还是在对Redis的了解和学习上。学完本篇,你将了解Redi...
    99+
    2023-09-08
    redis 数据库 redis实战 缓存预热 微服务
  • Java开发 - Quartz初体验
    目录​​​​​​​ 前言 Quartz 什么是Quartz Quartz作用 Quartz结构 表达式 案例 Quartz实战 添加依赖 创建Job类 创建配置类 测试代码 扩展练习 结语 前言 在上一篇博客中,我们对单点登录有了初步了...
    99+
    2023-09-07
    Quart 任务调度 scheduling Job JobDetail
  • Java开发 - SpringCache初体验
    前言 早些时候,博主介绍过Redis的使用:Java开发 - Redis初体验,Redie是基于缓存的一项技术,对于Redis,博主此处不再赘述,不了解的可以去看这篇文章,但Redis缓存并不是顶峰,本文要讲的内容就是Redis的辅助工具:...
    99+
    2023-09-05
    Redis SpringCache 缓存 CacheManager Cacheable
  • Java开发 - Elasticsearch初体验
    目录 前言 什么是es? 为什么要使用es? es查询的原理? es需要准备什么?  es基本用法 创建工程 添加依赖 创建操作es的文件 使用ik分词插件 Spring Data 项目中引入Spring Data 添加依赖 添加配置 创建...
    99+
    2023-09-05
    elasticsearch 大数据 搜索引擎 es 微服务
  • Python Metaclass 初探
    先以一个大牛的一段关于Python Metapgramming的著名的话来做开头: Metaclasses are deeper magic than 99% of users should ever worry about. If yo...
    99+
    2023-01-31
    Python Metaclass
  • React-three-fiber使用初体验
    目录React-three-fiber引入canvasuseFrameLightscamera设置React-three-fiber npm init -y npm install ...
    99+
    2023-05-19
    React-three-fiber使用 React-three-fiber初体验
  • javascriptThree.js创建文字初体验
    目录效果开始创建文本首先创建字体加载器加载字体库创建文字几何体计算文字几何体外边界矩形创建镜像文字创建半透明平面渲染关于文本构造器参数当curveSegments设置越低时,可以看到...
    99+
    2024-04-02
  • Exchange 2007使用初体验(3
    大家可以看到,在Exchange 2007中,邮箱的种类多了很多,在这里我们只是选择默认的“用户邮箱”,然后点“下一步”: 功能虽然一样,但界面明显比在“AD用户和计算机”中更加的漂亮和合理。填写好相应的信息以后,点“下一...
    99+
    2023-01-31
    初体验 Exchange
  • ChatGPT Python SDK开发指南:提升对话体验的技巧
    ChatGPT Python SDK开发指南:提升对话体验的技巧引言:ChatGPT是OpenAI推出的一款强大的对话生成模型,它能够生成流畅、富有逻辑的自然语言回复。在使用ChatGPT进行对话交互的过程中,如何提升用户体验,让对话更加具...
    99+
    2023-10-27
    ChatGPT Python SDK 对话体验
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作