How to connect a cdrom device to a kvm/qemu domain (using command-line tools)?

Solution 1:

If you defined no CDROM when you created your virtual machine, you can attach the device even to a running domain (virtual machine) by running the following command:

virsh attach-disk testbed /dev/sr0 hdc --type cdrom

If you already defined a CDROM, but it pointed to an ISO image, in my experience, you can still run the same command. The hdcpart needs to match the block device you have in the testbed virtual machine.

When you want to point to an ISO image again, you replace /dev/sr0 to the filename on the host, something like

virsh attach-disk testbed ~/virtio-win-0.1-22.iso hdc --type cdrom

The documentation suggests using virsh update-device, but it is more labour to create an XML definition something like:

<disk type='block' device='cdrom'>
  <driver name='qemu' type='raw'/>
  <source dev='/dev/sr0'/>
  <target dev='hdc' bus='ide'/>

If you are into this way, save something like that into a file (say ~/cdrom-real.xml) and then fire:

virsh update-device testbed ~/cdrom-real.xml

Solution 2:

Use virsh's qemu-monitor-command to pass the eject and change commands down to qemu.

First use "info block" to get qemu's device name for your cdrom.

virsh # qemu-monitor-command mirage --hmp --cmd "info block"
drive-virtio-disk0: type=hd removable=0 file=/home/daoist/mirage/mirage.qcow2 ro=0 drv=raw encrypted=0
drive-ide0-0-0: type=cdrom removable=1 locked=0 file=/home/daoist/iso/en_windows_7_ultimate_with_sp1_x64_dvd_u_677332.iso ro=1 drv=raw encrypted=0

So in my case I'm interested in drive-ide0-0-0. So to change the disk, do this:

virsh # qemu-monitor-command mirage --hmp --cmd "eject drive-ide0-0-0"
virsh # qemu-monitor-command mirage --hmp --cmd "change drive-ide0-0-0 /path/to/new.iso"
virsh #

Solution 3:

Regarding the "info block" command above, the correct way to call it is like this:

 virsh qemu-monitor-command <domain> --hmp --cmd "info block"


 virsh qemu-monitor-command windows44407 --hmp --cmd "info block"