在KVM主机和虚拟机之间共享目录

时间:2024-06-15 13:07:02

执行以下步骤:

(1)在host OS上面创建新的目录和在这个目录里面创建一个文件。

root@kvm:~# mkdir /tmp/shared
root@kvm:~# touch /tmp/shared/file

(2)在停止KVM的实例后,添加下面的配置

root@kvm:~# virsh edit kvm1
...
<devices>
...
<filesystem type='mount' accessmode='passthrough'>
<source dir='/tmp/shared'/>
<target dir='tmp_shared'/>
</filesystem>

...
</devices>
...
Domain kvm1 XML configuration edited.

(3)启动VM虚拟机:

root@kvm:~# virsh start kvm1
Domain kvm1 started

(4)执行以下命令连接控制台

root@kvm:~# virsh console kvm1
Connected to domain kvm1
Escape character is ^] Debian GNU/Linux debian ttyS0 debian login: root
Password:
...

(5)确保9p和virtio内存驱动已经加载

root@debian:~# lsmod | grep 9p
9pnet_virtio
9pnet 9pnet_virtio
virtio_ring virtio_pci,virtio_balloon,9pnet_virtio
virtio virtio_pci,virtio_balloon,9pnet_virtio

(6)挂载共享的目录到/mnt

root@debian:~# mount -t 9p -o trans=virtio tmp_shared /mnt

(7)列出刚刚挂载的东西

root@debian:~# mount | grep tmp_shared
tmp_shared on /mnt type 9p (rw,relatime,sync,dirsync,trans=virtio)

(8)查看下我们在第一步创建的文件是否能看的到

root@debian:~# ls -la /mnt/
total
drwxr-xr-x root root Mar : .
drwxr-xr-x root root Mar : ..
-rw-r--r-- root root Mar : file