libguestfs简介

libguestfs is a set of tools for accessing and modifying virtual machine (VM) disk p_w_picpaths.

libguestfs官网介绍:http://libguestfs.org/


libguestfs使用

一、命令行工具

yum install -y libguestfs libguestfs-tools  # 安装命令行工具包,命令是guestfish,raw和qcow2格式的镜像guestfish都可以编辑
[root@compute5 Downloads]guestfish -a centos6.5.img -i  # -a:是attach  -i:会自动mount镜像里的分区
[root@compute5 Downloads]# guestfish -a centos6.5.img   # 不使用-i,要手动挂载分区
Welcome to guestfish, the libguestfs filesystem interactive shell for
editing virtual machine filesystems.
Type: 'help' for help on commands
      'man' to read the manual
      'quit' to quit the shell
><fs> run 
><fs> mount /dev/sda2 /
# 你可以使用这样的shell script来编辑某个文件
[root@compute5 Downloads]# guestfish -a centos6.5-test-2.img -i << eof
rm /etc/udev/rules.d/70-persistent-net.rules 
eof
guestfish下没有类似sed的工具,不过提供了类似augtool的命令


二、python调用

yum install -y libguestfs python-libguestfs  # 安装python库
# 这里举个例子:往虚拟机镜像里上传一个文件
[root@compute5 Downloads]# vim test.py 
#!/usr/bin/env python
import guestfs               # python加载guestfs库
g = guestfs.GuestFS(python_return_dict=True)         # 创建一个GuestFS实例
g.add_drive_opts("centos6.5-test-2.img",format="qcow2",readonly=0)  # 挂载img到libguestfs
g.launch()        # 后台运行libguestfs
partitions = g.list_partitions()             #  获取所有分区
g.mount(partitions[1],'/')                    # 第二个分区挂载到根目录
g.upload("/etc/resolv.conf", "/etc/resolv.conf")     # g.upload("src文件", "dst文件"),看不懂,英文没学好
g.close()        # 虽然会自动close,还是再手工close最保险



针对windows镜像,使用kpartx。

kpartx -a <p_w_picpath_id>
yum install ntfsprogs ntfs-3g



参考链接

http://libguestfs.org/guestfs-python.3.html