#!/bin/bash


#kvm的安装路径

KVM_DIR="/home/bozhong" 

 

###分别获取ip、子网掩码、网关

IP_ADDR="ifconfig |grep inet| sed -n '1p'|awk '{print $2}'|awk -F ':' '{print $2}'"

MASK="ifconfig |grep inet| sed -n '1p'|awk '{print $4}'|awk -F ':' '{print $2}'"

GATEWAY="route -n | grep eth0 | grep UG | awk '{print $2}'"


###检查机器的cpu是否支持kvm虚拟化###

egrep -o '(vmx|svm)' /proc/cpuinfo 

if [ $? != "0" ]; then

      echo "this machine is not supported kvm!!!" 

      exit 1;

fi


#创建虚拟机目录

mkdir -p $KVM_DIR

cd $KVM_DIR



###安装KVM、virt管理软件和网桥管理工具###

apt-get install qemu-kvm libvirt-bin virt-manager bridge-utils 

if [ $? != "0" ]; then

echo "error! kvm is not installed correctly."

exit 2;

fi


###添加用户名到libvirtd、kvm###

adduser `id -un` libvirtd 

adduser `id -un` kvm 


###确定kvm是否完全安装成功###


virsh -c qemu:///system list 

if [ $? != "0" ]; then

echo "error! kvm is not installed correctly!!!"

exit 3;

fi


###增加一个叫br0的虚拟网卡,让这个网卡可以和eth0以太网的网卡做桥接###


cat >/etc/network/interfaces <<EOF

auto lo

iface lo inet loopback

auto eth0

iface eth0 inet manual

auto br0

iface br0 inet static

address \$IP_ADDR

netmask \$MASK

gateway \$GATEWAY

bridge_ports eth0

EOF



#保存,重启网卡设置

/etc/init.d/networking restart

if [ $? != "0" ]; then

echo "error! network is not restarted correctly."

exit 4;

fi


mkdir $KVM_DIR/ubuntu


#把iso文件mount一个目录

sudo mount -o loop /home/bozhong/ubuntu-12.04.4-server-amd64.iso /home/bozhong/ubuntu

if [ $? != "0" ]; then

echo "error! iso mount is not successful !!!"

exit 5;

fi


#创建ubuntu12.04虚拟机

cd $KVM_DIR/ubuntu


virt-install --connect=qemu:///system \

--name bozhong4 \

--ram 1024 \

--vcpus=1 \

--os-type=linux \

--os-variant=ubuntuprecise \

--accelerate \

--hvm \

--disk path=/home/bozhong/bozhong4.img,size=6,bus=virtio \

--location /home/bozhong/ubuntu \

--extra-args='console=tty0 console=ttyS0' \

--network bridge=br0,model=virtio \

--graphics none



我在步骤中直接手动指定ip、网关和子网掩码了然后

安装过程中选择 mirror 那一步,地区我选择的是 china

Choose a mirror of the Ubuntu archive


安装结束之后,可以用vnc或者命令连接kvm虚拟终端

例如:virsh console xxx

我采用 ssh hui@172.16.3.85


帮助文档:


https://help.ubuntu.com/community/KVM/Installation


http://wiki.ubuntu.org.cn/Kvm%E6%95%99%E7%A8%8B#.E5.AE.89.E8.A3.85.E5.87.86.E5.A4.87


http://loveworld.blog.51cto.com/5092260/990511



http://speakingbaicai.blog.51cto.com/5667326/1161964

http://blog.csdn.net/panfengyun12345/article/details/16878873


http://blog.163.com/bull_linux/blog/static/21388114220133234041190/


http://blog.fens.me/vps-kvm/