最近因为要重搭容灾环境,之前部署了将近380台的虚拟机其中85%靠上需要回收掉,部分虚拟机需要保留(很烦哎.....),业务部门提供了需要保留的虚拟机的IP,然后保留的大概有60台左右吧(好烦呀),手动回收.....,这可不是俺的风格,来吧,脚本躁动起来吧(https://mianbao.cn.com/thread-358-1-1.html):
import os import time import pprint from pysphere import VIProperty from pysphere.vi_task import VITask from connect import vcenter_connection as con from pysphere.resources import VimService_services as VI from pysphere.vi_virtual_machine import VIVirtualMachine s = con() class VM_Del(): def __init__(self,s): self.__s = s self.__vm = None self.__ip_path = os.path.join(os.path.dirname(__file__),‘ip.txt‘) def GetVmInfo(self): prope = [‘guest.ipAddress‘,‘name‘,‘summary.runtime.powerState‘,] dict_key = {‘guest.ipAddress‘:‘ip‘,‘name‘:‘name‘,‘summary.runtime.powerState‘:‘power‘} props = s._retrieve_properties_traversal(property_names=prope, obj_type=‘VirtualMachine‘) vm = {} one_vm = dict() for item in props: for p in item.PropSet: one_vm[dict_key.get(p.Name)] = p.Val vm[one_vm.get(‘name‘)] = {‘ip‘:one_vm.get(‘ip‘),‘power‘:one_vm.get(‘power‘)} print vm return vm def GetIpWhiteList(self): ip_list = list() with open(self.__ip_path) as file: all_ip_white_list = file.readlines() [ip_list.append(x.strip()) for x in all_ip_white_list] return ip_list def PowerDownVm(self,vm): self.__vm = self.__s.get_vm_by_name(vm) self.__vm.power_off() def Done(self): white_list = self.GetIpWhiteList() all_vm = self.GetVmInfo() for x,y in all_vm.items(): if y.get(‘ip‘,None) in white_list: pass elif ‘WG_‘ in x: print x if y.get(‘power‘) == ‘poweredOn‘: self.PowerDownVm(x) print ‘ |--->Poeroff.....OK‘ time.sleep(5) print ‘ |---->del.....start‘ self.DelVm() print ‘ |----->del.........OK‘ time.sleep(10) else: print ‘%s power status is %s‘ % (x, y.get(‘power‘)) print white_list def DelVm(self): request = VI.Destroy_TaskRequestMsg() _this = request.new__this(self.__vm._mor) _this.set_attribute_type(self.__vm._mor.get_attribute_type()) request.set_element__this(_this) ret = s._proxy.Destroy_Task(request)._returnval #Wait for the task to finish task = VITask(ret, s) status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR]) if status == task.STATE_SUCCESS: print " |------>VM successfully deleted from disk" elif status == task.STATE_ERROR: print "Error removing vm:", task.get_error_message() if __name__ == "__main__": vm_del = VM_Del(s) vm_del.Done()
实验脚本,很粗糙,随后会优化,效果如下,脚本输出:
VC任务显示:
本文出自 “面包” 博客,请务必保留此出处http://mianbao.blog.51cto.com/12784768/1920384
原文地址:http://mianbao.blog.51cto.com/12784768/1920384