To be a better coder
分类: LINUX
2021-07-27 10:03:40
修改qcow2镜像里的内容,可以通过guestmount工具来进行,guestmount工具包含在libguestfs工具集内,所以先执行 yum install libguestfs libguestfs-tools -y安装。
下面看怎么修改一个qcow2镜像内的内容,使用如下命令
# guestmount -a
两个主要的参数说明下,其他参数可通过guestmount --help查看
-a 指定待挂载的镜像文件
-m 指定镜像文件中的客户系统的磁盘分区,如果分区写得不对,会有错误提示
$ guestmount -a centos7.qcow2 -m /dev/sda2 /mnt libguestfs: error: mount_options: mount exited with status 32: mount: /dev/sda2 is write-protected, mounting read-only mount: unknown filesystem type '(null)' guestmount: ‘/dev/sda2’ could not be mounted. guestmount: Did you mean to mount one of these filesystems? guestmount: /dev/sda1 (vfat) guestmount: /dev/sda2 (unknown) guestmount: /dev/sda3 (ext4)
也可以用virt-filesystems工具来查看镜像里的磁盘分区信息
$ virt-filesystems -a centos7.qcow2
/dev/sda1
/dev/sda3
sudo到root用户下执行
# guestmount -a centos7.qcow2 -m /dev/sda3 /mnt
libguestfs: error: could not create appliance through libvirt.
Try running qemu directly without libvirt using this environment variable:
export LIBGUESTFS_BACKEND=direct
Original error from libvirt: Cannot access storage file '/root/centos7.qcow2' (as uid:52479, gid:52479): Permission denied [code=38 int1=13]
报上面的错,是因为libvirt环境异常,按提示执行下面的语句
# export LIBGUESTFS_BACKEND=direct
再重新执行guestmount,命令行执行成功
# guestmount -a centos7.qcow2 -m /dev/sda3 /mnt
这时,centos7.qcow2的/dev/sda3分区就挂载到宿主机的/mnt目录了,cd /mnt/进去后可以看到镜像文件里的文件系统,接下来就可以对里面的文件进行改写了
# cd /mnt/
# ls
bin boot dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
按需要改写,比如我当时的一个需求是在镜像里增加ttyS1设备
# echo ttyS1 >> etc/securetty
# 修改 boot/grub2/grub.cfg
完成后,卸载
# guestunmount /mnt