-
Notifications
You must be signed in to change notification settings - Fork 2
/
batch_vm
217 lines (181 loc) · 6.74 KB
/
batch_vm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# -*- coding=utf-8 -*-
'''
@Created on 2016年4月6日
@author: MianBao
@author_web: Mianbao.cn.com
@此脚本主要用于批量开通vmware虚拟机
@参数说明
@name:虚拟机名称前缀
@template:虚拟机模板名字 @请确保其唯一性
@node:节点名称
@num:虚拟机开通数量
@network:虚拟机开通之后网卡连接哪个虚拟交换机
'''
import os
import ssl
import sys
import getpass
import readline
import platform
from mianbao import VIServer
from mianbao import MORTypes, VIServer, VITask, VIProperty, VIMor, VIException
os.system('clear')
def IS_Windows():
'''
@判断运行此脚本的环境是windows还是Linux
'''
return True if "Windows" in platform.system() else False
def Path(file = None):
'''
@获取脚本运行的目录
'''
root_path = os.path.abspath(os.path.dirname(__file__))
return os.path.join(root_path, file) if file else root_path
def Connect(Host,User,Pwd):
'''
@用于和VC建立连接
@Host:VCenter地址
@User:vCenter用户名
@Pwd:密码
'''
if IS_Windows():
ssl._create_default_https_context = ssl._create_unverified_context
Server = VIServer()
try:
Server.connect(Host, User, Pwd)
except Exception,e:
print str(e).split(':')[1]
return 1
return Server if Server.is_connected() else 1
def Check_Cluster(Server):
Cluster = Server.get_clusters()
return True if len(Cluster) > 0 else False
def Find_VM_Node(Server,node):
'''
@查找用于开通虚拟机的节点资源ID
'''
node_resource_id = None
print ' |--开始查找节点:%s......' % node
if Check_Cluster(Server):
for dc_mor, dc_name in Server.get_datacenters().items():
print ' |--正在 %s 数据中心中查找 .....' % dc_name
Cluster_id_dict = dict()
for c_mor, c_name in Server.get_clusters(from_mor=dc_mor).items():
print ' |--正在 %s 数据中心下的 %s 集群中搜索..... ' % (dc_name,c_name)
Cluster_id_dict[c_name] = c_mor
for h_mor, h_name in Server.get_hosts(from_mor=c_mor).items():
if h_name == node:
resource = Server.get_resource_pools(c_mor)
node_resource_id = resource.keys()[0]
print ' |--已搜索到此节点,返回其资源池ID为:%s' % node_resource_id
print ' |--正在获取此节点磁盘情况......'
host_id = h_mor
node_data_id = Get_Node_Disk_Id_List(Server,h_mor,h_name)
if node_resource_id is None:
node_resource_id,node_data_id,host_id = Single_Node_search(Server,node)
else:
node_resource_id,node_data_id,host_id = Single_Node_search(Server,node)
return node_resource_id,node_data_id,host_id
def Single_Node_search(Server,ip):
'''
@遍历无群集时单节点信息
'''
print ' |--检测到数据中心无群集!.....'
nodes = Server._get_managed_objects("ComputeResource")
for x,y in nodes.items():
if y == ip:
resource_id = x
resource_id = Server.get_resource_pools(resource_id).keys()[0]
for m,n in Server.get_hosts().items():
if n == ip:
node_data_id = Get_Node_Disk_Id_List(Server,m,n)
host_id = m
return resource_id,node_data_id,host_id
def Get_Node_Disk_Id_List(server,d_mor,d_name):
'''
@获取当前主机的磁盘id
'''
p = VIProperty(server, d_mor)
node_disk_id = list()
print '\033[1;31;40m 请选择您要放置虚拟机的磁盘:\033[0m'
for ds in p.datastore:
node_disk_id.append(ds._obj)
i = 1
dict_id=dict()
for node_id in node_disk_id:
Get_Node_Disk_Info(server,node_id,i)
dict_id['%s' % i] = node_id
i+=1
return dict_id
def Get_Node_Disk_Info(server,id,i):
'''
@获取节点的硬盘空间
'''
for ds_mor, name in server.get_datastores().items():
props = VIProperty(server, ds_mor)
if ds_mor == id:
print '\033[1;32;40m |--%s %s : 总:%s 余:%s \033[0m' % (i,name, unit_convert_start_kb(props.summary.capacity),unit_convert_start_kb(props.summary.freeSpace))
def Generate_name(name,vm_num):
'''
@生成虚拟机名字
'''
name_list = list()
[ name_list.append(str(name)+str(y)) for y in range(1,int(vm_num)+1) ]
return name_list
def VM_Clone(Server,template_name,name_list,new_vm):
'''
@克隆虚拟机
'''
vm = Server.get_vm_by_name(template_name)
index = 1
print '\033[1;31;40m'
for y in name_list:
new_vm['name'] = y
print '正在开通第 %s 台,名称为:%s ' % (index,y)
try:
vm.clone(**new_vm)
except Exception,e:
print str(e).split(':')[1]
index += 1
print '\033[0m'
def unit_convert_start_kb(v1):
'''
@主要用于硬盘单位换算
'''
v1 = int(v1)
li = ['bytes','Kb','M','G','T','P']
a = 0
while v1 > 1024:
v1 = v1/1024
a += 1
return str(round(v1,2))+str(li[a])
def Mains():
'''
@主函数,主要用于流程控制
'''
new_vm=dict()
print '\033[1;31;40m' + '*='*60
print '欢迎大家使用面包(Mianbao.cn.com)虚拟机批量开通脚本!'.rjust( 50 )
print '*='*60+'\033[0m'
VCenter_ip = raw_input('\033[1;32;40m 请输入VCenter地址:\033[0m')
vCenter_user = raw_input('\033[1;32;40m 请输入vCenter用户名:\033[0m')
vCenter_pwd = getpass.getpass('\033[1;32;40m 请输入vCenter的密码:\033[0m')
print ' |--开始连接vCenter..... '
Server = Connect(VCenter_ip,vCenter_user,vCenter_pwd)
while Server == 1:
vCenter_pwd = getpass.getpass('\033[1;32;40m 请输入vCenter的密码:\033[0m')
Server = Connect(VCenter_ip,vCenter_user,vCenter_pwd)
print ' |--已成功连接vCenter.....'
node = raw_input('\033[1;32;40m 要把虚拟机开在哪个服务器上:\033[0m')
new_vm['resourcepool'],node_data_id,new_vm['host'] = Find_VM_Node(Server,node)
node_disk_id = raw_input('\033[1;32;40m 请输入硬盘位置的编号:\033[0m')
new_vm['datastore'] = node_data_id.get(node_disk_id)
new_vm['sync_run'] = True
name_add = raw_input('\033[1;32;40m 输入虚拟机名称前缀:\033[0m')
num = raw_input('\033[1;32;40m 请输入要开通的虚拟机数量:\033[0m')
name_list = Generate_name(name_add,num)
template_name = raw_input('\033[1;32;40m 请输入模板的虚拟机名称:\033[0m')
VM_Clone(Server,template_name,name_list,new_vm)
Server.disconnect()
if __name__ == "__main__":
Mains()