You can create, delete, run, stop, and manage your virtual machines from the command line, using a tool called virsh. Virsh is particularly useful for advanced Linux administrators, interested in script or automating some aspects of managing their virtual machines

Installing

Install virsh:

sudo apt-get install libvirt-bin

Connecting

Connect to your hypervisor. This can be local, or even remote. In most cases, if you want to manage VMs running on the local hypervisor:

$ virsh connect qemu:///system
Connecting to uri: qemu:///system

Listing VMs

$ virsh list
 Id Name                 State
----------------------------------
  1 foo                  running

Creating a Virtual Machine

Virtual Machines managed by virsh are created by describing the virtual machine in a libvirt XML file, and importing that XML file into virsh.

You can export the XML of an existing virtual machine:

$ virsh dumpxml foo > /tmp/foo.xml
Connecting to uri: qemu:///system

And then edit /tmp/foo.xml, which should be rather straightforward. For more information about libvirt XML format, see:

Once you have an XML file describing the new virtual machine you want to create, import it into virsh, and run it immediately:

$ virsh create /tmp/foo_new.xml 
Connecting to uri: qemu:///system
Domain foo_new created from /tmp/foo_new.xml
$ virsh list
Connecting to uri: qemu:///system
 Id Name                 State
----------------------------------
  3 foo_new              running

Alternatively, if you want to define it, but not run it, you could have used:

$ virsh define /tmp/foo_new.xml

Working with a Running Virtual Machine

Once a virtual machine is running, you can manage it in many different ways, such as:

$ virsh start foo

$ virsh reboot foo

$ virsh shutdown foo

$ virsh suspend foo

$ virsh resume foo

You can also affect the memory, dynamically attach devices, interfaces, modify the networking configuration, etc. This guide in this wiki page is clearly not comprehensive. For a complete description of virsh commands, see:

$ man virsh

Console

Sometimes, it's useful to attach to the console of a running VM, to obtain debugging information, etc.

$ virsh console foo
Connected to domain foo
Escape character is ^]

Details

To view the details about a particular virtual machine:

$ virsh dumpxml foo

These can be saved to a file, modified, and imported again using:

$ virsh define foo

Deleting a Virtual Machine

To delete a virtual machine, first terminate it (if running), and then undefine it:

$ virsh destroy foo_new
$ virsh undefine foo_new

More Information

For more complete documentation on virsh, see:

KVM/Virsh (last edited 2014-04-03 22:33:31 by 79-113-255-204)