before.安装软件

yum install libvirt libguestfs-tools qemu-kvm qemu-img
yum groupinstall Virtualization "Virtualization Client" -y
yum -y install libvirt libguestfs-tools -y


1.下载一个最小的centos6.5的iso文件

wget http://mirrors.163.com/centos/6.5/isos/x86_64/CentOS-6.5-x86_64-minimal.iso

2.创建一个空的镜像文件

qemu-img create -f qcow2 /tmp/CentOS6.5-working.qcow2 10G

3.创建虚拟机

qemu-img create -f qcow2 /tmp/CentOS6.5-working.qcow2 10G 
virt-install --virt-type=kvm --name=CentOS6.5 --ram=1024 \
--cdrom=/tmp/CentOS-6.5-x86_64-minimal.iso \
--disk=/tmp/CentOS6.5-working.qcow2,format=qcow2 \
--graphics=vnc,listen=0.0.0.0 --noautoconsole \
--os-type=linux --os-variant=rhel6

4.vnc远程安装,地址端口5900;分区只分一个,挂载到“/”,格式为ext4;

#重启后执行命令开启虚拟机
virsh start centos6.5

5.初始化

#!/bin/bash
# add the EPEL repo and update
rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
#yum -y update
# install cloud-init
yum -y install cloud-utils cloud-init parted git acpid
chkconfig acpid on
 
# install linux rootfs resize
cd /tmp
git clone https://github.com/flegmatik/linux-rootfs-resize.git
cd linux-rootfs-resize
./install
if [[ $? -eq 0 ]];then
  cd /tmp
  rm -rf linux-rootfs-resize
else
  exit
fi
 
#change sshd port
sed -i 's/^#Port 22/Port 65530/g' /etc/ssh/sshd_config
# clean up the network interface stuff
rm /etc/udev/rules.d/70-persistent-net.rules
sed -i '/HWADDR/d' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i '/UUID/d' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i '/^ONBOOT/ s/no/yes/g' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i '/^NM_CONTROLLED/ s/yes/no/g' /etc/sysconfig/network-scripts/ifcfg-eth0
echo "NOZEROCONF=yes" >> /etc/sysconfig/network
# graft up grub
sed -i 's/timeout=5/timeout=0/g' /boot/grub/menu.lst
sed -i '/^\skernel/ s/$/ console=tty0 console=ttyS0,115200n8/' /boot/grub/menu.lst
# say something cute in /etc/motd
echo "This is Openstack-CentOS-6" >> /etc/motd
# notify we're halting
echo "Halting instance in 5 seconds!"
sleep 5
# halt the instance
halt

6.善后操作

#清除网络相关硬件生成信息
virt-sysprep -d centos6.5
#压缩镜像
virt-sparsify --compress /tmp/CentOS6.5-working.qcow2 CentOS6.5-working_1.qcow2

7.完成