查看: 1425|回复: 0

[Pysphere] 修改虚拟机IP

[复制链接]

440

主题

642

帖子

5080

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
5080
发表于 2016-5-20 14:04:15 | 显示全部楼层 |阅读模式
  1. from pysphere import *
  2. from pysphere.resources import VimService_services as VI
  3. from pysphere.vi_task import VITask

  4. server = VIServer()
  5. server.connect("192.168.1.1", "administrator", "passwd")
  6. target_vm = "test_vm"
  7. #vm = server.get_vm_by_path("[datastore] path/to/file.vmx")
  8. vm_obj = server.get_vm_by_name(target_vm)
  9. ipAddress = "192.168.1.2"
  10. hostName = "test_vm"
  11. domain_name = "mydomail.local"
  12. netmask = '255.255.255.0'

  13. vm_obj.power_off()
  14. # Customize hostname and IP address
  15. request = VI.CustomizeVM_TaskRequestMsg()
  16. _this = request.new__this(vm_obj._mor)
  17. _this.set_attribute_type(vm_obj._mor.get_attribute_type())
  18. request.set_element__this(_this)
  19. spec = request.new_spec()
  20. globalIPSettings = spec.new_globalIPSettings()
  21. spec.set_element_globalIPSettings(globalIPSettings)
  22. # NIC settings, I used static ip, but it is able to set DHCP here, but I did not test it.
  23. nicSetting = spec.new_nicSettingMap()
  24. adapter = nicSetting.new_adapter()
  25. fixedip = VI.ns0.CustomizationFixedIp_Def("ipAddress").pyclass()
  26. fixedip.set_element_ipAddress(ipAddress)
  27. adapter.set_element_ip(fixedip)
  28. adapter.set_element_subnetMask(netmask)
  29. nicSetting.set_element_adapter(adapter)
  30. spec.set_element_nicSettingMap([nicSetting,])
  31. identity = VI.ns0.CustomizationLinuxPrep_Def("identity").pyclass()
  32. identity.set_element_domain("domain_name")
  33. hostName = VI.ns0.CustomizationFixedName_Def("hostName").pyclass()
  34. hostName.set_element_name(target_vm.replace("_", ""))
  35. identity.set_element_hostName(hostName)
  36. spec.set_element_identity(identity)
  37. request.set_element_spec(spec)
  38. task = server._proxy.CustomizeVM_Task(request)._returnval

  39. vi_task = VITask(task, server)
  40. status = vi_task.wait_for_state([vi_task.STATE_SUCCESS, vi_task.STATE_ERROR])
  41. if status == vi_task.STATE_SUCCESS:
  42.     print "VM successfully reconfigured"
  43. elif status == vi_task.STATE_ERROR:
  44.     print "Error reconfiguring vm:", vi_task.get_error_message()

  45. #Disconnect from the server
  46. server.disconnect()
复制代码


选一人白头,择一城终老
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 加入我们

本版积分规则

!jz_fbzt! !jz_sgzt! !jz_xgzt! 快速回复 !jz_sctz! !jz_fhlb!
快速回复 返回顶部 返回列表