Vmware 控制脚本

时间:2023-12-29 20:26:32
#_*_ coding:utf8 _*_
import sys,time
import yaml
import re
import os
import ssl
import random
import ConfigParser
from unittest import TestCase from pysphere import VIServer, VIProperty, MORTypes, VIException, FaultTypes, \
VMPowerState, ToolsStatus class VmDP:
def __init__(self, host, user, password, **kwargs):
self.host = host
self.user = user
self.pwd = password self.server = VIServer()
self.server.connect(self.host, self.user, self.pwd)
self.kwargs = kwargs #虚拟机的资源信息显示
def vm_info(self):
all_hosts = self.server.get_hosts() # 查看物理机
datacenter = self.server.get_datacenters() # 查看数据中心
cluster = self.server.get_clusters() # 查看集群
store = self.server.get_datastores() # 查看存储
resource = self.server.get_resource_pools() # 资源池信息
vm_name = self.server.get_registered_vms() # 所有虚拟机
vm_power_on = self.server.get_registered_vms(status='poweredOn') # 所有已上电的虚拟机
vm_power_off = self.server.get_registered_vms(status='poweredOff') # 所有未上电的虚拟机 print("----物理主机信息----")
for k, v in all_hosts.items():
print("[主机名ID]:%s -- [IP地址]:%s" % (k, v)) print("----数据中心信息----")
for k, v in datacenter.items():
print("[数据中心ID]:%s -- [数据中心名字]:%s" % (k, v)) print("----存储信息----")
for k, v in store.items():
print("[存储ID]:%s -- [存储名字]:%s" %(k,v)) print("----集群信息----")
for k, v in cluster.items():
print("[集群ID]:%s -- [集群名字]:%s" %(k,v)) print("----资源池信息----(分组信息)")
for k, v in resource.items():
print("[资源池ID]:%s -- [资源路径]:%s" %(k,v)) def install_vm_info(self, vm_name):
if vm_name is None:
print("没有参数vm_name.请输入参数:install_vm_info(vm_name)")
exit(1)
tmp = filter(self.server, vm_name)
vm = self.server.get_vm_by_path(tmp)
os_info = vm.get_properties()['guest_full_name']
guest_id = vm.get_properties()['guest_id']
cpu_nu = vm.get_properties()['num_cpu']
disk_capacity = str(vm.get_properties()['disks'][0]['capacity'] / 1024 / 1024) + "g"
device_cd = vm.get_properties()['devices'][16000]["label"]
device_network = vm.get_properties()['devices'][4000]["label"]
mem_nu = str(vm.get_properties()['memory_mb'] / 1024) + "g"
vm_ip = vm.get_properties()['ip_address']
vm_mac = vm.get_properties()['net'][0]['mac_address']
vnc_network = vm.get_properties()['net'][0]['network']
print("""
\t\t==========================================================
\t\t虚拟机安装的系统信息 : %s
\t\t==========================================================""" % os_info) print("""
==============
虚拟机基础信息
==============
主机名: %s\t\t虚拟机名: %s\t\t虚拟机ID: %s
IP地址: %s\t\tMAC地址: %s\t\t虚拟网络: %s
==============
虚拟机硬件配置
==============
CPU数: %s\t内存: %s\t硬盘: %s\tCDROM: %s\t网卡: %s""" % (host_name, vm_in_name, guest_id, \
vm_ip, vm_mac, vnc_network, cpu_nu, mem_nu, disk_capacity, device_cd, device_network)) # 过滤出虚拟机的 存储和虚拟机名
def filter(obj, v):
hosts = obj.get_registered_vms()
if v is not None:
for host in hosts:
res = re.findall(r'\[\S*\] ' + v + '\/' + v + '\.vmx', host)
# res = re.findall(r''+'\[\w*\] '+ v + '\/\w*.vmx',host)
if res:
return res[0] def vm_dis(self):
if self.server.is_connected():
self.server.disconnect() def network_info(self):
return os.system("/usr/bin/ezmomi list --type Network") def vm_all_host(self):
return os.system("/usr/bin/ezmomi list --type VirtualMachine") def clone_template(self, kwargs):
k = kwargs
print k
os.system("ezmomi clone --template %s --hostname %s --cpus %s --mem %s --ips %s" \
% (k['template'], k['hostname'], k['cpu'] ,k['mem'], k['new_vm_ip']))
return True if __name__ == "__main__":
# 关闭ssl证书验证
ssl._create_default_https_context = ssl._create_unverified_context config_name = 'config.yaml'
config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), config_name)
config = yaml.load(file(config_file))
v = VmDP(config['vmware']['host'], config['vmware']['user'], config['vmware']['pwd'])
v.vm_info()
clone_conf = {'template': 'template-test',
'hostname': 'test_zhang',
'cpu': '4',
'mem': '4',
'new_vm_ip': '10.101.255.208'}
v.clone_template(clone_conf)