Sunday, October 23, 2016

use virsh and qemu to run a vm

1- install packages
$ sudo apt-get install qemu openvswitch-switch  libvirt-bin gvncviewer

2- create image test.raw
$ qemu-img create -f raw -o size=40G test.raw

3- create bridge br0 and set ip address
$ sudo ovs-vsctl add-br br0
$ sudo ifconfig br0 up

4- create xml file for a vm, the xml file called image.xml
the file set, cdrom: map to /home/user1/livecd/ubuntu-remix.iso
disk: map to  /home/user1/virsh-kvm/test.raw
network: br0
the content is below

<domain type="qemu">
  <memory unit="KiB">524288</memory>
  <currentMemory unit="KiB">524288</currentMemory>
  <vcpu placement="static">1</vcpu>
    <type arch="x86_64" machine="pc-0.12">hvm</type>
    <boot dev="cdrom"/>
  <clock offset="utc"/>
    <disk type="file" device="disk">
      <driver name="qemu" type="raw"/>
      <source file="/home/user1/virsh-kvm/test.raw"/>
      <target dev="vda" bus="virtio"/>
      <address type="pci" domain="0x0000" bus="0x00" slot="0x04" function="0x0"/>
    <disk type="file" device="cdrom">
      <driver name="qemu" type="raw"/>
      <source file="/home/user1/livecd/ubuntu-remix.iso"/>
      <target dev="hdc" bus="ide"/>
      <address type="drive" controller="0" bus="1" target="0" unit="0"/>
    <controller type="ide" index="0">
      <address type="pci" domain="0x0000" bus="0x00" slot="0x01" function="0x1"/>
    <interface type="bridge">
      <mac address="52:52:f2:55:32:39"/>
      <source bridge="br0"/>
      <virtualport type="openvswitch">
      <model type="virtio"/>
      <address type="pci" domain="0x0000" bus="0x00" slot="0x03" function="0x0"/>
    <serial type="pty">
      <target port="0"/>
    <console type="pty">
      <target type="serial" port="0"/>
    <input type="mouse" bus="ps2"/>
    <graphics type="vnc" port="-1" autoport="yes"/>
      <model type="cirrus" vram="9216" heads="1"/>
      <address type="pci" domain="0x0000" bus="0x00" slot="0x02" function="0x0"/>
    <memballoon model="virtio">
      <address type="pci" domain="0x0000" bus="0x00" slot="0x05" function="0x0"/>

5- create vm from the xml file
$ sudo virsh create image.xml

6- list running vm
$ sudo virsh list
 Id    Name                           State
 17    ubuntuzesty                    running

$ sudo virsh  list --all

7- find out the vnc port of the running vm
$ sudo virsh vncdisplay ubuntuzesty

8- to connect to vnc use the following command
$  gvncviewer localhost

- snapshot of vnc connect to the running vm

9- finally after you finish using the vm, you can destroy it
$ sudo virsh destroy ubuntuzesty

to use it again, start from step 5

No comments:

Post a Comment