kvm

kvm系統(tǒng)要求

1核心
2G內(nèi)存
6G硬盤
# 1.查看硬件是否支持虛擬化
lscpu # 查看cpu信息
# Virtualization:        VT-x 
# Intel CPU:VT-x
# AMD CPU: AMD-v
# 如果沒有就在bios中開啟

# 2.查看操作系統(tǒng)是否支持
egrep 'svm|vmx' /proc/cpuinfo # 在flags中包含svm或者vmx表示支持

# 3.查看內(nèi)核模塊是否有kvm
# 如果沒有該模塊,零時(shí)使用 `modprobe kvm`加載kvm模塊(模塊存在于/lib/modules/xxxx/kernel目錄下);
# 永久生效,在/etc/modules-load.d/ 創(chuàng)建.conf的文件,并把模塊名寫在文件中
lsmod | grep kvm

虛擬化主機(jī)部署

Centos

yum grouplist # 查看支持的分組以及已安裝的分組
#實(shí)際安裝的組可以通過  yum groupinfo '虛擬化*'   查看安裝的分組以及分組包含的軟件包
# 安裝的主要軟件包 yum install virt-manager qemu-img qemu-kvm qemu-kvm-tools libvirt virt-install bridge-utils
yum -y groupinstall '虛擬化*' 

# 虛擬化主機(jī)部署驗(yàn)證
# 查看libvirtd的狀態(tài)
systemctl status libvirtd
lsmod | grep kvm

# 開啟ipv4轉(zhuǎn)發(fā)
# CentOS防火墻開啟masquerade后即開啟包轉(zhuǎn)發(fā)功能
# 也可以通過命令sysctl net.ipv4.ip_forward=1手動開啟包轉(zhuǎn)發(fā)功能。
firewall-cmd --add-masquerade # 當(dāng)前開啟
firewall-cmd --permanent --add-masquerade # 永久開啟
# 查看ipv4轉(zhuǎn)發(fā)是否開啟
sysctl net.ipv4.ip_forward # 如果=1為開啟,=0則未開啟
yum -y install iptables-services # 安裝iptables
systemctl disable firewalld.service
systemctl stop firewalld.service
systemctl enable iptables
systemctl start iptables
# 清空iptables規(guī)則
iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -t raw -F
iptables -t secure -F

systemctl restart libvirtd # 將kvm虛擬機(jī)的轉(zhuǎn)發(fā)規(guī)則重新寫入iptables

Ubuntu

sudo apt update
sudo apt upgrade
sudo apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils virtinst virt-manager virt-top

kvm相關(guān)安裝包及其作用

qemu-kvm          主要的KVM程序包
python-virtinst   創(chuàng)建虛擬機(jī)所需要的命令行工具和程序庫
virt-manager      GUI虛擬機(jī)管理工具
virt-top          虛擬機(jī)統(tǒng)計(jì)命令
virt-viewer       GUI連接程序,連接到已配置好的虛擬機(jī)
libvirt           C語言工具包,提供libvirt服務(wù)
libvirt-client    虛擬客戶機(jī)提供的C語言工具包
virt-install      基于libvirt服務(wù)的虛擬機(jī)創(chuàng)建命令
bridge-utils      創(chuàng)建和管理橋接設(shè)備的工具

虛擬機(jī)安裝

virt-install 命令行方式安裝

安裝命令

qemu-img create -f qcow2 /localVM/tp/ubuntuTP.qcow2 40G

virt-install \
        --name ubuntuTP \
        --vcpus 1,maxvcpus=4 \
        --disk path=/localVM/tp/ubuntuTP.qcow2 \
        --os-variant=ubuntu22.04 \
        --memory 2048,maxmemory=8192 \
        --cdrom=/myfile/iso/ubuntu-22.04-live-server-amd64.iso \
        --graphics vnc,password=asdqwe@,listen=0.0.0.0,port=5920,keymap=en-us \
        --network network=default,model=virtio,driver.iommu=on \
        --noautoconsole # 不要自動嘗試連接到客戶控制臺

virt-install \
        --name centosTP \
        --vcpus 1,maxvcpus=4 \
        --disk path=/vm/tml/centosTP.qcow2 \
        --os-variant=centos7 \
        --memory 1024,maxmemory=8192 \
        --cdrom=/public/CentOS-7-x86_64-Minimal-2009.iso \
        --graphics vnc,password=asdqwe@,listen=0.0.0.0,port=5920,keymap=en-us \
        --network network=default,model=virtio,driver.iommu=on \
        --network bridge=brwifi,model=virtio,driver.iommu=on \
        --noautoconsole

 #--disk  先用qume-img創(chuàng)建磁盤,disk選項(xiàng)只指定path引用就可以,如果不預(yù)先創(chuàng)建,這里指定參數(shù)創(chuàng)建,則會指定多大就會占用多大空間
  #--os-variant virt-install --osinfo list 查看支持的系統(tǒng)標(biāo)識

# 安裝windows如果需要支持半虛擬化驅(qū)動disk
--disk path=/vm/win10.qcow2,bus=virtio \
--disk path=半虛擬化驅(qū)動的路徑,device=floppy \
--network bridge=virbr0,model=virtio

磁盤操作

qemu-img create -f qcow2 /disk1.qcow2 40G # 創(chuàng)建磁盤
virsh attach-disk dom名字  - -source 創(chuàng)建的磁盤路基  - -target vdb  - -cache writeback  - -subdriver qcow2  - -persistent # 向vm添加磁盤

參數(shù)解讀(virt-install --help)
使用 virt-install --option=? 查看此選項(xiàng)的詳細(xì)設(shè)置

 -n NAME, --name NAME  Name of the guest instance
  --memory MEMORY       Configure guest memory allocation. Ex:
                        --memory 1024 (in MiB)
                        --memory memory=1024,currentMemory=512
  --vcpus VCPUS         Number of vCPUs to configure for your guest. Ex:
                        --vcpus 5
                        --vcpus 5,maxvcpus=10,cpuset=1-4,6,8
                        --vcpus sockets=2,cores=4,threads=2
  --cpu CPU             CPU model and features. Ex:
                        --cpu coreduo,+x2apic
                        --cpu host-passthrough
                        --cpu host
  --metadata METADATA   Configure guest metadata. Ex:
                        --metadata name=foo,title="My pretty title",uuid=...
                        --metadata description="My nice long description"
  --xml XML             Perform raw XML XPath options on the final XML. Example:
                        --xml ./cpu/@mode=host-passthrough
                        --xml ./devices/disk[2]/serial=new-serial
                        --xml xpath.delete=./clock

Installation Method Options:
  --cdrom CDROM         CD-ROM installation media
  -l LOCATION, --location LOCATION
                        Distro install URL, eg. https://host/path. See man page for specific distro examples.
  --pxe                 Boot from the network using the PXE protocol
  --import              Build guest around an existing disk image
  -x EXTRA_ARGS, --extra-args EXTRA_ARGS
                        Additional arguments to pass to the install kernel booted from --location
  --initrd-inject INITRD_INJECT
                        Add given file to root of initrd from --location
  --unattended [UNATTENDED]
                        Perform an unattended installation
  --install INSTALL     Specify fine grained install options
  --reinstall DOMAIN    Reinstall existing VM. Only install options are applied, all other VM configuration options are ignored.
  --cloud-init [CLOUD_INIT]
                        Perform a cloud image installation, configuring cloud-init
  --boot BOOT           Configure guest boot settings. Ex:
                        --boot hd,cdrom,menu=on
                        --boot init=/sbin/init (for containers)
  --idmap IDMAP         Enable user namespace for LXC container. Ex:
                        --idmap uid.start=0,uid.target=1000,uid.count=10

OS options:
  --os-variant OS_VARIANT, --osinfo OS_VARIANT
                        The OS being installed in the guest.
                        This is used for deciding optimal defaults like VirtIO.
                        Example values: fedora29, rhel7.0, win10, ...
                        Use '--osinfo list' to see a full list.

Device Options:
  --disk DISK           Specify storage with various options. Ex.
                        --disk size=10 (new 10GiB image in default location)
                        --disk /my/existing/disk,cache=none
                        --disk device=cdrom,bus=scsi
                        --disk=?
  -w NETWORK, --network NETWORK
                        Configure a guest network interface. Ex:
                        --network bridge=mybr0
                        --network network=my_libvirt_virtual_net
                        --network network=mynet,model=virtio,mac=00:11...
                        --network none
                        --network help
  --graphics GRAPHICS   Configure guest display settings. Ex:
                        --graphics spice
                        --graphics vnc,port=5901,listen=0.0.0.0
                        --graphics none
  --controller CONTROLLER
                        Configure a guest controller device. Ex:
                        --controller type=usb,model=qemu-xhci
                        --controller type=scsi,model=virtio-scsi
  --input INPUT         Configure a guest input device. Ex:
                        --input tablet
                        --input keyboard,bus=usb
  --serial SERIAL       Configure a guest serial device
  --parallel PARALLEL   Configure a guest parallel device
  --channel CHANNEL     Configure a guest communication channel
  --console CONSOLE     Configure a text console connection between the guest and host
  --hostdev HOSTDEV     Configure physical USB/PCI/etc host devices to be shared with the guest
  --filesystem FILESYSTEM
                        Pass host directory to the guest. Ex:
                        --filesystem /my/source/dir,/dir/in/guest
                        --filesystem template_name,/,type=template
  --sound [SOUND]       Configure guest sound device emulation
  --audio AUDIO         Configure host audio backend for sound devices
  --watchdog WATCHDOG   Configure a guest watchdog device
  --video VIDEO         Configure guest video hardware.
  --smartcard SMARTCARD
                        Configure a guest smartcard device. Ex:
                        --smartcard mode=passthrough
  --redirdev REDIRDEV   Configure a guest redirection device. Ex:
                        --redirdev usb,type=tcp,server=192.168.1.1:4000
  --memballoon MEMBALLOON
                        Configure a guest memballoon device. Ex:
                        --memballoon model=virtio
  --tpm TPM             Configure a guest TPM device. Ex:
                        --tpm /dev/tpm
  --rng RNG             Configure a guest RNG device. Ex:
                        --rng /dev/urandom
  --panic PANIC         Configure a guest panic device. Ex:
                        --panic default
  --shmem SHMEM         Configure a guest shared memory device. Ex:
                        --shmem name=shmem0
  --memdev MEMDEV       Configure a guest memory device. Ex:
                        --memdev dimm,target.size=1024
  --vsock VSOCK         Configure guest vsock sockets. Ex:
                        --vsock cid.auto=yes
                        --vsock cid.address=7
  --iommu IOMMU         Configure an IOMMU device. Ex:
                        --iommu model=intel,driver.aw_bits=48

Guest Configuration Options:
  --iothreads IOTHREADS
                        Set domain <iothreads> and <iothreadids> configuration.
  --seclabel SECLABEL, --security SECLABEL
                        Set domain seclabel configuration.
  --keywrap KEYWRAP     Set guest to perform the S390 cryptographic key management operations.
  --cputune CPUTUNE     Tune CPU parameters for the domain process.
  --numatune NUMATUNE   Tune NUMA policy for the domain process.
  --memtune MEMTUNE     Tune memory policy for the domain process.
  --blkiotune BLKIOTUNE
                        Tune blkio policy for the domain process.
  --memorybacking MEMORYBACKING
                        Set memory backing policy for the domain process. Ex:
                        --memorybacking hugepages=on
  --features FEATURES   Set domain <features> XML. Ex:
                        --features acpi=off
                        --features apic=on,apic.eoi=on
  --clock CLOCK         Set domain <clock> XML. Ex:
                        --clock offset=localtime,rtc_tickpolicy=catchup
  --pm PM               Configure VM power management features
  --events EVENTS       Configure VM lifecycle management policy
  --resource RESOURCE   Configure VM resource partitioning (cgroups)
  --sysinfo SYSINFO     Configure SMBIOS System Information. Ex:
                        --sysinfo host
                        --sysinfo bios.vendor=MyVendor,bios.version=1.2.3,...
  --qemu-commandline QEMU_COMMANDLINE
                        Pass arguments directly to the QEMU emulator. Ex:
                        --qemu-commandline='-display gtk,gl=on'
                        --qemu-commandline env=DISPLAY=:0.1
  --launchSecurity LAUNCHSECURITY, --launchsecurity LAUNCHSECURITY
                        Configure VM launch security (e.g. SEV memory encryption). Ex:
                        --launchSecurity sev

Virtualization Platform Options:
  -v, --hvm             This guest should be a fully virtualized guest
  -p, --paravirt        This guest should be a paravirtualized guest
  --container           This guest should be a container guest
  --virt-type VIRT_TYPE
                        Hypervisor name to use (kvm, qemu, xen, ...)
  --arch ARCH           The CPU architecture to simulate
  --machine MACHINE     The machine type to emulate

Miscellaneous Options:
  --autostart           Have domain autostart on host boot up.
  --transient           Create a transient domain.
  --destroy-on-exit     Force power off the domain when the console viewer is closed.
  --wait [WAIT]         Minutes to wait for install to complete.
  --autoconsole AUTOCONSOLE
                        Configure guest console auto connect. Example:
                        --autoconsole text
                        --autoconsole graphical
                        --autoconsole none
  --noautoconsole       Don't automatically try to connect to the guest console
  --noreboot            Don't boot guest after completing install.
  --print-xml [XMLONLY]
                        Print the generated domain XML rather than create the guest.
  --dry-run             Run through install process, but do not create devices or define the guest.
  --check CHECK         Enable or disable validation checks. Example:
                        --check path_in_use=off
                        --check all=off
  -q, --quiet           Suppress non-error output
  -d, --debug           Print debugging information

kvm常用文件位置

默認(rèn)nat網(wǎng)絡(luò)配置文件

# 使用virsh net-edit default 命令修改
# /etc/libvirt/qemu/networks/default.xml
<network>
  <name>default</name>
  <uuid>0b385979-f3a4-4d10-8d24-fdbbed0307a3</uuid>
  <forward mode='nat'/>
  <bridge name='virbr0' stp='on' delay='0'/>
  <mac address='52:54:00:dd:bc:c8'/>
  <ip address='192.168.122.1' netmask='255.255.255.0'>
    <dhcp>
      <range start='192.168.122.2' end='192.168.122.254'/>
    </dhcp>
  </ip>
</network>

存儲池配置文件(存虛擬機(jī)的磁盤鏡像)

# virsh pool-edit ubuntu22.04 修改
# /etc/libvirt/storage/
# /etc/libvirt/storage/autostart
<pool type='dir'>
  <name>ubuntu22.04</name>
  <uuid>66414018-799e-404e-b930-503662a1f632</uuid>
  <capacity unit='bytes'>0</capacity>
  <allocation unit='bytes'>0</allocation>
  <available unit='bytes'>0</available>
  <source>
  </source>
  <target>
    <path>/vm/tp/ubuntu22.04</path>
  </target>
</pool>

虛擬機(jī)配置文件

# /etc/libvirt/qemu/

內(nèi)存氣球

內(nèi)存氣球

kvm常用命令

# 客戶機(jī)(虛擬機(jī))相關(guān)virt*
virt-top :查看客戶機(jī)負(fù)載
virt-install:安裝客戶機(jī)系統(tǒng)

# virsh程序是管理virsh客戶機(jī),用來創(chuàng)建、修改、暫停和關(guān)閉域。它也可以用來列出當(dāng)前的域
virsh list [--all] : 查看所有的客戶機(jī)
virsh autostart 
virsh net-edit 網(wǎng)絡(luò)配置名稱:修改網(wǎng)絡(luò)配置
virsh setvcpus 虛擬機(jī)名稱 2 --live:修改指定虛擬機(jī)的cpu核數(shù)
virsh dumpxml 虛擬機(jī)名稱  | grep memballon -C2:查看內(nèi)存氣球的配置

qemu-agent-command
在虛擬機(jī)上安裝 QEMU 客戶機(jī)代理

apt install qemu-guest-agent
systemctl enable qemu-guest-agent
virsh qemu-agent-command --domain ubuntuTP '{"execute":"guest-network-get-interfaces"}' #查ip

新建模版機(jī)后,部署腳本

#!/usr/bin/env bash
set -euo pipefail
declare -r highPerformanceSSDPath="/vm/hpssd"
declare -r normalSSDPath="/vm/nomralssd"
declare -A tmplDiskMap=(["b"]="/vm/tml/centos/centosTP.qcow2" ["a"]="/vm/tml/ubuntu22.04/ubuntuTP.qcow2")
declare -A tmplXmlMap=(["b"]="/vm/tml/centos/centosTP.xml" ["a"]="/vm/tml/ubuntu22.04/ubuntutp.xml")
declare -A vmDiskTypePath=(["a"]="/vm/hpssd/" ["b"]="/vm/nomralssd/")

# export LIBGUESTFS_DEBUG=1 LIBGUESTFS_TRACE=1

function identityCheck() {
    if [ $(whoami) != root ]; then
        echo 請以root身份運(yùn)行
        exit 1
    fi
}

function systemMenu() {
    cat <<-EOF
        --------------------------------
        A.部署Ubuntu22.02系統(tǒng)
        B.部署CentOS7.9系統(tǒng)
        --------------------------------
    EOF
}

function systemEnvMenu() {
    cat <<-EOF
        --------------------------------
        A.高性能磁盤主機(jī)
        B.普通SSD磁盤主機(jī)
        --------------------------------
    EOF
}
function deployVM() {
    chooseSystem=""
    choseSystemDisk=""
    hostName=""
    iplast=""

    while :; do
        systemMenu
        read -p 請選擇要部署的系統(tǒng): chooseSystem
        chooseSystem=$(echo $chooseSystem | tr 'A-Z' 'a-z')
        if [[ "$chooseSystem" =~ [a|A|b|B] ]]; then
            break
        fi
        echo 沒有這個(gè)選項(xiàng)\"${chooseSystem}\",請重新選擇
    done

    while :; do
        systemEnvMenu
        read -p 請選擇系統(tǒng)磁盤類型: choseSystemDisk
        choseSystemDisk=$(echo $choseSystemDisk | tr 'A-Z' 'a-z')
        if [[ "$choseSystemDisk" =~ [a|A|b|B] ]]; then
            break
        fi
        echo 沒有這個(gè)選項(xiàng)\"${choseSystemDisk}\",請重新選擇
    done

    while :; do
        read -p 請輸入主機(jī)名稱: hostName
        if [ "$hostName" != "" ]; then
            break
        fi
    done

    while :; do
        read -p 請輸入ip地址的最后一位: iplast
        if [[ "$iplast" =~ (^[1-9][0-9]$)|(^[5-9]$)|(^1[0-9]{2}$)|(^25[0-4]$)|(^2[0-4][0-9]$) ]]; then
            break
        fi
        echo ip:\"${iplast}\"非法,請重新輸入
    done

    vmdiskDir=${vmDiskTypePath["$choseSystemDisk"]}${hostName}
    if [ ! -d "$vmdiskDir" ]; then
        mkdir -p $vmdiskDir
    fi
    vmdisk=${vmdiskDir}/${hostName}.qcow2
    vmxml=${vmdiskDir}/${hostName}.xml

    if [ -e "$vmdisk" ]; then
        echo -e "\033[31m${vmdisk}已存在\033[0m"
        exit 1
    fi
    vmuuid=$(uuidgen)
    ip="192.168.158.${iplast}"
    vmmac1="52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed -r 's/^(..)(..)(..)(..).*$/\1:\2:\3:\4/')"
    vmmac2="52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed -r 's/^(..)(..)(..)(..).*$/\1:\2:\3:\4/')"
    echo -e "\033[32m虛擬機(jī)名字是${hostName},虛擬機(jī)ID是:${vmuuid},虛擬機(jī)磁盤是:${vmdisk},虛擬機(jī)mac是:${vmmac1},ip是:${ip}】\033[0m"

    tmplDiskPath=${tmplDiskMap[$chooseSystem]}
    cp ${tmplXmlMap[$chooseSystem]} $vmxml
    qemu-img create -f qcow2 -b $tmplDiskPath -F qcow2 $vmdisk

    if [ "$chooseSystem" = "b" ]; then
        guestmount -a $vmdisk -m /dev/centos_centostp/root /vm/temp
        sed -ri "s#IPADDR=192.168.158.2#IPADDR=${ip}#" /vm/temp/etc/sysconfig/network-scripts/ifcfg-eth0
        sed -ri 's#UUID=29104de9-6297-4b33-aa51-891aa5073e6b##' /vm/temp/etc/sysconfig/network-scripts/ifcfg-eth0
        sed -ri 's#UUID=835c4284-a9fc-4325-bb97-e9fda3bccfea##' /vm/temp/etc/sysconfig/network-scripts/ifcfg-eth1
        sed -ri "s#centostp#${hostName}#" /vm/temp/etc/hostname
    elif [[ "$chooseSystem" = "a" ]]; then
        guestmount -a $vmdisk -m /dev/sda4 /vm/temp
        sed -ri "s#192.168.158.3#${ip}#" /vm/temp/etc/netplan/00-installer-config.yaml
        sed -ri "s#ubuntutp#${hostName}#" /vm/temp/etc/hostname
    fi

    guestunmount /vm/temp

    sed -ri "s#vmname#${hostName}#" $vmxml
    sed -ri "s#vmuuid#${vmuuid}#" $vmxml
    sed -ri "s#vmdisk#${vmdisk}#" $vmxml
    sed -ri "s#vmmac1#${vmmac1}#" $vmxml
    sed -ri "s#vmmac2#${vmmac2}#" $vmxml
    virsh define $vmxml
    echo -e "\033[32m部署完成\033[0m"

}
identityCheck
deployVM

拓展

系統(tǒng)預(yù)備工具

PXE
kickstart
cobbler

部署工具

ansible
puppet
saltstack
chef

持續(xù)集成及持續(xù)發(fā)布工具

git
github
gitlab
gogs
jenkins
docker
kubernetes
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一.虛擬化技術(shù)的介紹 (1)虛擬化技術(shù)類型: 1.主機(jī)虛擬化:xen,kvm.virtualbox.openv2....
    楠人幫閱讀 2,173評論 0 5
  • CentOS6.5 安裝KVM虛擬機(jī) vnc安裝 因?yàn)榘惭b系統(tǒng)還是需要圖形界面去進(jìn)行相關(guān)操作的,所以我們先配置一個(gè)...
    Evil_cosey閱讀 913評論 0 1
  • kvm實(shí)驗(yàn) 環(huán)境準(zhǔn)備,我這里使用虛擬機(jī)進(jìn)行模擬,先設(shè)定好虛擬化 進(jìn)入系統(tǒng)查看是否支持虛擬化 KVM:Kernel-...
    早_wsm閱讀 1,005評論 0 2
  • 1、搭建kvm虛擬環(huán)境 ?KVM是一個(gè)混合類型的VMM,它能夠以模擬方式支持硬件的完全虛擬 化,也能夠在Guest...
    stephe_c閱讀 3,304評論 0 0
  • 一、實(shí)現(xiàn)LVS+Keepalived高可用集群 1、架構(gòu)圖 2、編譯安裝keepalived 選項(xiàng)--disabl...
    Ken_7988閱讀 1,466評論 1 1

友情鏈接更多精彩內(nèi)容