您好,登錄后才能下訂單哦!
最近因為要重搭容災環境,之前部署了將近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任務顯示:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。