2011年9月9日 星期五

直接操作 KVM 虛擬硬碟檔 (撰寫程式)

可自行撰寫程式, 方便直接操作 KVM 虛擬硬碟檔, 程式操作如下 :

1. 執行 mntvm.sh 程式, 掛載 GW100.vmdk 虛擬硬碟檔, 此虛擬硬碟檔會被掛載到 /tmp/GW100.vmdk 這目錄

$ sudo ./mntvm.sh -m GW100.vmdk

掛載 GW100.vmdk 成功

2.檢視 虛擬硬碟檔 內容

$ ll /tmp/GW100.vmdk/
總計 32
drwxr-xr-x 5 root root 4096 2011-08-20 17:33 ./
drwxrwxrwt 13 root root 4096 2011-09-09 15:29 ../
drwxr-xr-x 3 root root 4096 2011-08-19 12:03 boot/
drwx------ 2 root root 16384 2011-08-19 12:03 lost+found/
drwxrwxr-x 3 xman staff 4096 2011-08-19 14:04 tce/

3. 懈載 虛擬硬碟檔

$ sudo ./mntvm.sh -u GW100.vmdk

懈載 GW100.vmdk 成功

mntvm.sh 程式
#!/bin/bash
#
# mntvm.sh (V 1.0)
# Date : 2011/08/29
#
# Copyright (C) 2010 "Sung-Ling Chen"  <kvm99.98@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/Licenses/>.
#
#####################################################################

# 執行前檢查
#---------------------------------------------------------------
[ "$USER" != "root" ] && echo "需要 root 權限" && exit 1

[ "$#" != 2 ] && echo 'mntvm [--mount|-m|--umount|-u] vm' && exit 1
cmd=$1
[ ${cmd%%[a-zA-Z]*} == '--' ] && cmd='\-\-'${cmd##*-}
[ ${cmd%%[a-zA-Z]*} == '-' ] && cmd='\-'${cmd##*-}

echo "--mount,-m,--umount,-u" | grep "$cmd" &>/dev/null
[ "$?" != "0" ] && echo "mntvm [--mount|-m|--umount|-u] vm" && exit 1

vmdk=$2

case  "$1" in
      '--mount' | '-m' )
          if [ -f /var/lib/libvirt/images/$vmdk ]; then
             [ -d /tmp/$vmdk ] && echo "$vmdk 已掛載" && exit 1
             echo -ne "\n掛載 $vmdk "
             kvm-nbd -c /dev/nbd0 /var/lib/libvirt/images/$vmdk &>/dev/null
             if [ "$?" == 0 ]; then
                sleep 2

                [ -d /tmp/$vmdk ] && rm -r /tmp/$vmdk
                mkdir /tmp/$vmdk

                mount /dev/nbd0p1 /tmp/$vmdk
                [ "$?" == 0 ] && echo -e "成功\n"
              fi
          else
             echo "找不到 /var/lib/libvirt/images/$vmdk 檔案"
             exit 1
          fi
            ;;
      '--umount' | '-u' )
          if [ -d /tmp/$vmdk ]; then
             umount /tmp/$vmdk
             [ "$?" == 0 ] && rm -r /tmp/$vmdk

             kvm-nbd -d /dev/"nbd0" &>/dev/null
             [ "$?" == 0 ] && echo -e "\n懈載 $vmdk 成功\n"
          else
             echo "找不到懈載 $vmdk 目錄"
             exit 1
          fi
           ;;
esac

echo ""
exit 0

沒有留言:

張貼留言