Jump directly to main content

Virsh Cheatsheet



Virsh is an extremely powerful tool for managing KVM/QEMU virtual machines. From restarting, to changing hardware, snapshotting, and cloning machines. I'll cover the basics of Virsh here, as it's all I personally use.

List VMs

virsh list

List all, including offline vms

virsh list --all

Start/Stop

virsh start $vm
virsh shutdown $vm
virsh reboot $vm

If the VM refuses to shutdown, etc. destroy performs an ungraceful shutdown

virsh destroy $vm

Autostart

virsh autostart $vm
virsh autostart $vm --disable

Rename

virsh domrename $vm $new_name

Delete

virsh undefine $vm

Delete Snapshots

If your VM has Snapshots it won't delete as simply, so delete those first

List the snapshots

virsh snapshot-list --domain $vm

And delete each snapshot with the following

virsh snapshot-delete --domain $vm --snapshotname $snapshot

Deleting with all storage

Delete the VM along with all the virtual storage

virsh undefine --domain $vm --remove-all-storage

Snapshots

Create

Save a snapshot of the VMs current state

virsh snapshot-create-as --domain $vm --name "$snapshot_name"

Restore/Revert

Revert the VM to the state it was in during the snapshot

virsh snapshot-revert $vm $snapshot_name

Delete Snapshot

Delete the snapshot, this doesn't delete anything else related to the VM

virsh snapshot-delete --domain $vm --snapshotname $snapshot_name

(TODO)Drive management

Resize virtual drives

Find the name of your drive.

virsh domblklist $vm

Resize with qemu

sudo qemu-img resize /location/drive.qcow2 +10G

Change Memory

In variantions of 512M, 1G, etc

virsh setmem $vm $ram

The amount of RAM the VM has assigned to it, this cannot be higher than the max, but can be altered on the fly (if I recall correctly).

virsh setmaxmem $vm $ram

The max mem sets the maximum amount of RAM the VM can use, and can only be set whilst the VM is offline

My recommendation here is to set a higher maxmem than you'd need, so if you do need to add some more RAM, it doesn't require any downtime.

Change vCPU cores

This is a little more tricky, as it involves editing the XML file

virsh edit $vm

Then edit the vcpus section, change between the tags

<vcpu placement='static'>$vcpus</vcpu>

Connect via serial/console

This is a means to connect to your VMs via terminal

virsh console $vm

To do this you will likely need to first run the following command on the VM itself. This won't be required if you created the VM with console, but best to double check.

systemctl enable serial-getty@ttyS0.service