Script to power on VM | Nutanix Community
Skip to main content
Looking for a simple script to Power on a shutdown Nutanix VM. Perhaps there is already a thread on this but I couldn't locate it if so.



Thanks!!
Hi, i have one.

I'm on my way to work and I send it to you, it's a very good python script.
Hi, i have one.

I'm on my way to work and I send it to you, it's a very good python script.




Copy and paste this code, save it with extension .py



Install python 3 interpreter and modules (argparse,getpass,requests,urllib3)



When setting the value --filter you can place the name of the VM to be turned on / off or you can turn off all VMs that start with a specific prefix.



Example:







Code:
code:
#!/usr/bin/env python3
import argparse
import getpass
import requests
import urllib3


urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


VERSION = '1.0.1'
TIMEOUT = 10


def change_power_state(url, username, password, filter, power_state):
base_url = url + "/PrismGateway/services/rest/v2.0"
try:
r = requests.get(base_url + f'/vms/?filter=vm_name%3D%3D.*{filter}.*',
auth=(username, password),
verify=False,
timeout=TIMEOUT)


if r.status_code == requests.codes.ok:


entities = r.json()['entities']

if len(entities) > 0:
vms = [(e['name'], e['uuid'], e['power_state']) for e in entities]




print(f"\nSelected VMs (Total: {len(vms)}):\n")




for vm in vms:
print(f"{vm[0]} (uuid: {vm[1]}, power_state: {vm[2]})")


confirm = None
while confirm not in ('yes', 'no', 'y', 'n'):
confirm = input(f'\nDo you want to modify the power state of all selected VMs to "{power_state}" (y/n): ').strip().lower()


if confirm in ['yes', 'y']:


print(f'\nModifying power states for VMs to "{power_state}":\n')


for vm in vms:
body = {"transition": f"{power_state}"}
r = requests.post(base_url + f'/vms/{vm[1]}/set_power_state/',
json=body, auth=(username, password),
verify=False,
timeout=TIMEOUT)
if r.status_code == requests.codes.created:
print(f"{vm[0]} (task_uuid: {r.json()['task_uuid']})")
else:
print("HTTP Error: " + str(r.status_code))

else:
print("\nOperation canceled.\n")
else:
print(f'\nNo VMs found using the filter criteria: "{filter}".\n')




else:
print("HTTP Error: " + str(r.status_code))
except Exception as e:
print(f"Error: {e}")


if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Nutanix VMs power state changer. Compatible with REST API v2.')




parser.add_argument('-v', '--version', action='version', version='%(prog)s v' + VERSION)
parser.add_argument('--url', required=True,
help='Nutanix REST API URL. Required. Ex: https://10.10.10.100:9440')
parser.add_argument('--username', required=True,
help='Nutanix REST API Username. Required.')
parser.add_argument('--password',
help='Nutanix REST API Password. Optional, is asked if it is omitted.')
parser.add_argument('--filter', required=True,
help='Filter string to search VMs by name. Required.')
parser.add_argument('--power_state', type = str.lower, required=True,
choices=['on', 'off', 'powercycle', 'reset', 'pause', 'suspend', 'resume', 'acpi_shutdown', 'acpi_reboot'],
help='Target power state to apply to selected VMs. Required.')


args = parser.parse_args()


password = args.password if args.password else getpass.getpass()


change_power_state(args.url, args.username, password, args.filter, args.power_state)

Use the Powershell Cmdlets (download from Prism/Central) and then fire up Powershell:



## Get the VM Unique Identifer for the VM you want to power on



$myvmname=Read-Host "Enter the name of the VM to power on"

$myvm= Get-NTNXVM | where {$_.vmname -eq $myvmname}

$myvmID = ($myvm.vmid.split(":"))[2]



## Power on the VM



Set-NTNXVMPowerOn -vmid $myvmID



Enjoy 🙂
@CitrixGuy1987 Good morning. Could I please ask you to confirm whether you are happy with my solution and please mark as Best Answer if so.



Many thanks



Andy @andymlloyd