Loading

使用 libvirt 快速创建 CentOS Stream 8 虚拟机

目标:快速创建一个 CentOS Stream 8 虚拟机,用于开发和测试。

  1. 获取 CentOS Stream 8 虚拟机磁盘镜像(qcow2)

    URL="https://cloud.centos.org/centos/8-stream/x86_64/images/$(curl -SsLf https://cloud.centos.org/centos/8-stream/x86_64/images/ | grep -Po '(?<=href=")CentOS-Stream-GenericCloud-8[^"]+.qcow2(?=")' | tail -1)"
    
    curl -Lo /var/lib/libvirt/images/centos-stream-8.qcow2 "${URL}"
    
  2. 修改虚拟机 root 密码为 12345

    docker run -it --rm \
      -v /var/lib/libvirt/images:/data \
      -w /data \
      -u "$(id -u):$(id -g)" \
      --entrypoint /usr/bin/env \
      bkahlert/libguestfs \
      -- virt-customize -a centos-stream-8.qcow2 --root-password password:12345 --uninstall cloud-init
    
  3. 修改虚拟机磁盘大小为 64G

    docker run -it --rm \
      -v /var/lib/libvirt/images:/data \
      -w /data \
      -u "$(id -u):$(id -g)" \
      --entrypoint /usr/bin/env \
      bkahlert/libguestfs \
      -- qemu-img resize centos-stream-8.qcow2 64G
    
  4. 创建虚拟机(4核8G,默认NAT网络)

    virt-install \
      --name centos-stream-8 \
      --os-type=Linux \
      --vcpus 4 \
      --memory 8192 \
      --disk /var/lib/libvirt/images/centos-stream-8.qcow2,bus=virtio --import \
      --network network=default,model=virtio \
      --graphics none \
      --noautoconsole
    
  5. SSH 登入虚拟机

    # 获取虚拟机 IP
    virsh domifaddr centos-stream-8
    # Name       MAC address          Protocol     Address
    # -------------------------------------------------------------------------------
    # vnet0      52:54:00:6c:41:39    ipv4         192.168.122.46/24
    
    IP=$(virsh domifaddr centos-stream-8 | grep -Po '\d+\.\d+\.\d+\.\d+')
    ssh "root@${IP}"
    # 密码为前面设置的 12345
    
  6. 【虚拟机内】拓展分区大小为磁盘大小

    # 拓展分区大小
    growpart /dev/vda 1
    xfs_growfs /
    
    # 确认分区大小
    df -Th
    
  7. 【虚拟机内】设置静态 IP 地址 & DNS

    sed -Ei -e '/^BOOTPROTO=.*$/d' -e '/^PERSISTENT_DHCLIENT=.*$/d' /etc/sysconfig/network-scripts/ifcfg-eth0
    
    cat >>/etc/sysconfig/network-scripts/ifcfg-eth0 <<EOF
    $(ip route | sed -En \
      -e 's|^[^/]+/([^ ]+) dev eth0 .* src ([^ ]+) .*$|PREFIX="\1"\nIPADDR="\2"|p' \
      -e 's|^default via ([^ ]+) dev eth0 .*$|GATEWAY="\1"|p')
    DNS1="223.5.5.5"
    DNS2="223.6.6.6"
    EOF
    
    # 确认配置无误
    cat /etc/sysconfig/network-scripts/ifcfg-eth0
    
    # 可选:设置 hostname 为 IP 地址
    hostnamectl set-hostname "$(hostname -I | sed 's|\.|-|g')"
    
  8. 转发虚拟机 SSH 服务端口到本地端口 22XXX

    # IP=$(virsh domifaddr centos-stream-8 | grep -Po '\d+\.\d+\.\d+\.\d+')
    LOCAL_PORT=22$(grep -Po '\d+$' <<< "${IP}" | xargs printf '%03d')
    
    docker run -d --name="ssh-${LOCAL_PORT}" --restart=always --net=host alpine/socat \
        tcp-listen:"${LOCAL_PORT}",fork,reuseaddr tcp4-connect:"${IP}":22
    
posted @ 2021-10-17 00:39  roy2220  阅读(300)  评论(0编辑  收藏  举报