前言

在结束安装Gentoo后,下一步就是要初始化我的实验环境了,我这里使用比较多的实验环境主要是在本机上创建虚拟机然后运行不同的软件和不同的环境。我常用的虚拟化软件如下:

虚拟化类型软件包
软件虚拟化app-emulation/virtualbox
全虚拟化app-emulation/qemu
半虚拟化app-emulation/xen
containerapp-emulation/docker

这几种虚拟化各有优点,我平时是使用virtualbox做测试环境,QEMU就更加贴近生产环境,半虚拟化是做Qubes On Gentoo的准备,容器是想要快速测试东西的时候使用的,后续也会作为基础了解一下K8S之类的。

这些直接使用可能有点不是很舒服为此我还需要以下工具来方便去管理虚拟机:

软件包描述
app-emulation/vagrant管理Virtualbox
app-emulation/libvirt管理QEMU虚拟机
app-admin/terraform使用libvirt的provider来管理QEMU虚拟机
app-admin/ansible批量管理虚拟机
app-admin/salt批量管理虚拟机

安装和配置Virtualbox环境

Virtualbox主要是放一些Whonix或者是测试的简单环境

安装Virtualbox

1
emerge --ask --verbose app-emulation/virtualbox app-emulation/virtualbox-additions app-emulation/virtualbox-extpack-oracle

为了普通用户可以正常使用Virtualbox还需要将用户添加到vboxusers组中

1
sudo usermod -aG vboxusers xena 

xena是我的用户名,这里需要替换成你的用户名。

如果更新内核之后发现Virtualbox无法正常使用的话运行以下命令之后重启即可:

1
emerge --ask --oneshot @module-rebuild

这里是重建了Virtualbox的模块。

至于Whonix如何在Virtualbox中的使用会在后面单独使用一篇文章来说明。

部署QEMU环境和创建虚拟机模板

QEMU是一个开源的软件虚拟化软件,即CPU、内存、网卡、硬盘全部都是虚拟出来的性能不会很好,但是后来有了KVM模块。这个KVM模块实现了对QEMU的加速。但是QEMU虚拟机只是一个单一的进程,管理起来很麻烦(Proxmox VE就是基于进程的QEMU管理)。好在Redhat发布了一个Libvirt的开源项目。Libvirt有API也有命令行的管理工具,大多数的KVM管理平台就是通过Libvirt来实现对KVM的管理。

我这里也将会使用Libvirt+QEMU的组合。

安装QEMU

在安装之前确保你的内核配置打开了KVM的选项

1
2
[*] Virtualization  --->
    <*>   Kernel-based Virtual Machine (KVM) support

如果你是Intel的CPU

1
2
[*] Virtualization  --->
    <M>   KVM for Intel processors support

如果你是AMD的CPU

1
2
[*] Virtualization  --->
    <M>   KVM for AMD processors support

构建新的内核并重启

额外选项(推荐)

如果你开启了vhost-net的USE

1
2
3
Device Drivers  --->
    [*] VHOST drivers  --->
            <*>   Host kernel accelerator for virtio net

高级网络支持

1
2
3
4
Device Drivers  --->
    [*] Network device support  --->
            [*]   Network core driver support
	            <*>   Universal TUN/TAP device driver support

桥接网络

1
2
3
4
[*] Networking support  --->
        Networking options  --->
	            <*> The IPv6 protocol
		                <*> 802.1d Ethernet Bridging

安装QEMU

1
emerge --ask --verbose app-emulation/qemu

如果你还需要其他架构的支持比如说aarch64ppc64或者是其他架构可以在/etc/portage/make.conf文件中加入如下内容:

1
2
QEMU_SOFTMMU_TARGETS="arm x86_64 sparc"
QEMU_USER_TARGETS="x86_64"

然后再去安装QEMU,当然还有一种方法是,使用/etc/portage/package.use/来添加USE 创建并编辑/etc/portage/package.use/qemu

1
nano -w /etc/portage/package.use/qemu

内容如下

1
2
app-emulation/qemu qemu_softmmu_targets_arm qemu_softmmu_targets_x86_64 qemu_softmmu_targets_sparc
app-emulation/qemu qemu_user_targets_x86_64

保存退出之后再安装qemu

这里qemu就可以使用了,如果你想要加入KVM的支持还需要将你的用户添加到kvm组

1
sudo usermod -aG kvm xena

Tips: 将xena替换成你的用户名

但是我平时使用都是用libvirt来管理虚拟机所以这里还需要安装一个libvirt,安装虚拟机要使用到一个包app-emulation/virt-manager如果你想要纯命令行这个包可以取消gtk的USE,我这里平时除了管理本地的虚拟机之外还需要管理其他的虚拟机这里就开启了。

1
sudo emerge --ask --verbose app-emulation/libvirt app-emulation/virt-manager

这里安装就算是完成了。

配置Libvirt

安装好基础的软件包之后我们接下来要配置一下libvirt 首先将当前的用户加入libvirt的组

1
sudo usermod -aG libvirt xena

Tips: 记得将xena更改成你的用户名

编辑/etc/libvirt/libvirtd.conf配置文件修改内容如下

1
2
3
4
5
auth_unix_ro = "none"
auth_unix_rw = "none"
unix_sock_group = "libvirt"
unix_sock_ro_perms = "0777"
unix_sock_rw_perms = "0770"

重启libvirtd

1
sudo /etc/init.d/libvirtd restart

加入开机启动

1
sudo rc-update add libvirtd default

配置网络

在网络这里如果你需求不大其实默认附送的那个网络也是可以使用的,但是我这里想要做一些隔离所以要对这些进行单独的设置。

我对网络的划分如下表:

网络名称网段说明网络类型
test172.11.0.0/22测试网络NAT
dev172.12.0.0/22开发网络NAT
oncall172.21.0.0/22线上网络NAT
data10.12.8.0/22数据网络Isolated

这里除了data网络之外其他都是NAT网络,通过NAT的方式让虚拟机能够上网。

首先我们dump一份xml文件出来并以此为基础进行修改

1
sudo virsh net-dumpxml default > default.xml

首先看看这个文件都有哪些信息

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
cat default.xml
<network>
  <name>default</name>
  <uuid>b9ebe716-d744-4706-bac8-5560f4e09344</uuid>
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
  <bridge name='virbr0' stp='on' delay='0'/>
  <mac address='52:54:00:b4:f0:b4'/>
  <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>
  • <name>这个标签声明了这个网络的名称
  • <uuid>这个标签声明了这个网络的uuid
  • <forward mode='nat'> 这个声明了转发的模式为NAT端口的范围是1024到65535
  • <bridge name>这个声明了网桥的名字 stp是防止回路
  • <mac address>这个是网卡的mac地址
  • <ip address> 这里是网络的网段以及dhcp池分配的范围从192.168.122.2到192.168.122.254

由此作为基础我们可以写第一个测试网络的配置文件

1
nano -w test.xml

内容如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<network>
  <name>test</name>
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
  <bridge name='virbr1' stp='on' delay='0'/>
  <ip address='172.11.0.1' netmask='255.255.252.0'>
    <dhcp>
      <range start='172.11.0.2' end='172.11.3.254'/>
    </dhcp>
  </ip>
</network>

这里删除了一些标签比如说<mac>,<uuid>之类的,更改了当前的这个网络名称,网桥的名字和dhcp地址。 保存退出之后创建网络:

1
sudo virsh net-define --file test.xml

启动网络

1
sudo virsh net-start test

如果想要这个网络随着libvirtd服务启动可以运行:

1
sudo virsh net-autostart test

查看网络

1
2
3
4
5
sudo virsh net-list
 Name      State    Autostart   Persistent
--------------------------------------------
 default   active   yes         yes
 test      active   yes         yes

以此为例子创建其他的网络:

dev

创建配置文件

1
nano -w  dev.xml

内容如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<network>
  <name>dev</name>
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
  <bridge name='virbr2' stp='on' delay='0'/>
  <ip address='172.12.0.1' netmask='255.255.252.0'>
    <dhcp>
      <range start='172.12.0.2' end='172.12.3.254'/>
    </dhcp>
  </ip>
</network>

创建网络

1
sudo virsh net-define --file dev.xml

启动网络

1
sudo virsh net-start dev

跟随libvirtd启动网络

1
sudo virsh net-autostart dev

oncall

创建并编辑oncall.xml文件

1
nano -w oncall.xml

内容如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<network>
  <name>oncall</name>
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
  <bridge name='virbr3' stp='on' delay='0'/>
  <ip address='172.21.0.1' netmask='255.255.252.0'>
    <dhcp>
      <range start='172.21.0.2' end='172.21.3.254'/>
    </dhcp>
  </ip>
</network>

创建网络

1
sudo virsh net-define --file oncall.xml

启动网络

1
sudo virsh net-start oncall

跟随libvirtd启动网络

1
sudo virsh net-autostart oncall

data

data是有点不一样的一个网络,这次我们不再使用NAT网络而使用isolated网络

创建data.xml文件,内容如下

1
2
3
4
5
6
7
8
9
<network>
  <name>data</name>
  <bridge name='virbr4' stp='on' delay='0'/>
  <ip address='10.12.8.1' netmask='255.255.252.0'>
    <dhcp>
      <range start='10.12.8.2' end='10.12.11.254'/>
    </dhcp>
  </ip>
</network>

创建网络:

1
sudo virsh net-define --file data.xml

启动网络

1
sudo virsh net-start data

随着libvirtd启动网络

1
sudo virsh net-autostart data

到这里我们的网络配置就完成了。

安装CentOS7虚拟机

这里就开始创建我们的虚拟机模板,这里以CentOS7为例子进行安装(目前我这里环境使用的最多的也是CentOS7)。

首先说明一下目录树结构

1
2
3
4
5
6
7
8
tree -d  workspace/
workspace/
├── qemu
│   ├── disk
│   ├── iso
│   └── net
└── virtualbox
    └── debian

我这里创建一个workspace的文件夹这个作为我主要的工作目录,下面的qemu就是存放qemu虚拟机的位置。 disk是存放硬盘的位置,iso就是存放iso的位置。

可以通过这条命令进行创建

1
mkdir -pv workspace/qemu/{disk,iso}

下载ISO

我们可以通过镜像站去下载ISO,以阿里云为例子:

1
2
cd workspace/qemu/iso
wget -c https://mirrors.aliyun.com/centos/7.9.2009/isos/x86_64/CentOS-7-x86_64-DVD-2009.iso

这里我下载的是完整的DVD版本如果你比较轻车熟路也可以选择其他的镜像。

创建虚拟机硬盘

这里使用的是qcow2格式的磁盘大小为40G

1
qemu-img create -f qcow2 workspace/qemu/disk/centos.qcow2 40G

创建虚拟机

在创建之前我们要创建一个目录,这个目录将会存放一些引导文件

1
sudo mkdir -pv /var/lib/libvirt/boot

创建虚拟机

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
sudo virt-install --virt-type=kvm \
--name=centos7 \
--memory=2048 \
--vcpus=2 \
--cpu=host-passthrough \
--location=/home/yafa/workspace/qemu/iso/CentOS-7-x86_64-Minimal-2009.iso \
--file=/home/yafa/workspace/qemu/disk/centos.qcow2,format=qcow2 \
--network network=default,model=virtio \
--nographics \
--extra-args console=ttyS0

接下来会进入文本安装模式中

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Installation

 1) [x] Language settings                 2) [!] Time settings
        (English (United States))                (Timezone is not set.)
 3) [!] Installation source               4) [!] Software selection
        (Processing...)                          (Processing...)
 5) [!] Installation Destination          6) [x] Kdump
        (No disks selected)                      (Kdump is enabled)
 7) [ ] Network configuration             8) [!] Root password
        (Not connected)                          (Password is not set.)
 9) [!] User creation
        (No user will be created)
  Please make your choice from above ['q' to quit | 'b' to begin installation |
  'r' to refresh]:

提示感叹号的需要进行配置,我们跟着提示进行配置

首先配置时间设定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
2
Time settings

Timezone: not set

NTP servers:not configured

 1)  Set timezone
 2)  Configure NTP servers
  Please make your choice from above ['q' to quit | 'c' to continue |
  'r' to refresh]:

这里没有设定时区和时间同步服务器我们这里两个都要设置一下。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Timezone settings

Available regions
 1)  Europe                 6)  Pacific               10)  Arctic
 2)  Asia                   7)  Australia             11)  US
 3)  America                8)  Atlantic              12)  Etc
 4)  Africa                 9)  Indian
 5)  Antarctica
Please select the timezone.
Use numbers or type names directly [b to region list, q to quit]:

这里我配置的时区是亚洲上海所以需要先输入2选择亚洲

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 1)  Aden                  29)  Hong_Kong             56)  Pontianak
 2)  Almaty                30)  Hovd                  57)  Pyongyang
 3)  Amman                 31)  Irkutsk               58)  Qatar
 4)  Anadyr                32)  Jakarta               59)  Qostanay
 5)  Aqtau                 33)  Jayapura              60)  Qyzylorda
 6)  Aqtobe                34)  Jerusalem             61)  Riyadh
 7)  Ashgabat              35)  Kabul                 62)  Sakhalin
 8)  Atyrau                36)  Kamchatka             63)  Samarkand
 9)  Baghdad               37)  Karachi               64)  Seoul
10)  Bahrain               38)  Kathmandu             65)  Shanghai
11)  Baku                  39)  Khandyga              66)  Singapore
12)  Bangkok               40)  Kolkata               67)  Srednekolymsk
13)  Barnaul               41)  Krasnoyarsk           68)  Taipei
14)  Beirut                42)  Kuala_Lumpur          69)  Tashkent
15)  Bishkek               43)  Kuching               70)  Tbilisi
16)  Brunei                44)  Kuwait                71)  Tehran
17)  Chita                 45)  Macau                 72)  Thimphu
18)  Choibalsan            46)  Magadan               73)  Tokyo
19)  Colombo               47)  Makassar              74)  Tomsk
20)  Damascus              48)  Manila                75)  Ulaanbaatar
21)  Dhaka                 49)  Muscat                76)  Urumqi
22)  Dili                  50)  Nicosia               77)  Ust-Nera
Press ENTER to continue

接下来是亚洲的一些城市,我们需要回车继续:

1
Use numbers or type names directly [b to region list, q to quit]: 65

这里提示我们输入在上面显示的城市编号,我们选择上海也就是65,回车确认。 这里会发现我们回到了主菜单我们按2重新进入时间设定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Time settings

Timezone: Asia/Shanghai

NTP servers:not configured

 1)  Change timezone
 2)  Configure NTP servers
  Please make your choice from above ['q' to quit | 'c' to continue |
  'r' to refresh]: 2
================================================================================
================================================================================
NTP configuration

NTP servers:no NTP servers have been configured

 1)  Add NTP server
  Please make your choice from above ['q' to quit | 'c' to continue |
  'r' to refresh]:

这里看到我们已经设置了时区我们接下来设置时间同步服务器。

我们这里使用的是阿里云的时间同步服务器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
 1)  Add NTP server
  Please make your choice from above ['q' to quit | 'c' to continue |
  'r' to refresh]: 1
================================================================================
================================================================================
Enter an NTP server address and press enter
ntp.aliyun.com
================================================================================
================================================================================
NTP configuration

NTP servers:
ntp.aliyun.com (checking status)

 1)  Add NTP server
 2)  Remove NTP server
  Please make your choice from above ['q' to quit | 'c' to continue |
  'r' to refresh]:

输入c继续安装。 接下来会进入到主菜单

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Installation

 1) [x] Language settings                 2) [x] Time settings
        (English (United States))                (Asia/Shanghai timezone)
 3) [x] Installation source               4) [x] Software selection
        (Local media)                            (Minimal Install)
 5) [!] Installation Destination          6) [x] Kdump
        (No disks selected)                      (Kdump is enabled)
 7) [ ] Network configuration             8) [!] Root password
        (Not connected)                          (Password is not set.)
 9) [!] User creation
        (No user will be created)
  Please make your choice from above ['q' to quit | 'b' to begin installation |
  'r' to refresh]:

这次我们要设置一下安装的磁盘

1
2
3
4
5
6
7
8
9
Probing storage...
Installation Destination

[x] 1) : 10 GiB (vda)

1 disk selected; 10 GiB capacity; 10 GiB free ...

  Please make your choice from above ['q' to quit | 'c' to continue |
  'r' to refresh]:

这里可以看到我们只有一个磁盘也就是vda输入c回车继续

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Autopartitioning Options

[ ] 1) Replace Existing Linux system(s)

[x] 2) Use All Space

[ ] 3) Use Free Space

Installation requires partitioning of your hard drive. Select what space to use
for the install target.

  Please make your choice from above ['q' to quit | 'c' to continue |
  'r' to refresh]:

这里问我们是使用全部的空间还是想让有空间富裕,这里选择2,并输入c回车

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Partition Scheme Options

[ ] 1) Standard Partition

[ ] 2) Btrfs

[x] 3) LVM

[ ] 4) LVM Thin Provisioning

Select a partition scheme configuration.

  Please make your choice from above ['q' to quit | 'c' to continue |
  'r' to refresh]:

这里是分区的方案

  1. 选项1是标准的分区,也就是直接在分区上创建文件系统
  2. 选项2是在分区上使用Btrfs的文件系统,再去创建子卷
  3. 选项3是使用LVM 在此基础上去创建文件系统
  4. 选项4是精简LVM配置

这里我们选择选项3并输入c回车后再次回到主界面

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Installation

 1) [x] Language settings                 2) [x] Time settings
        (English (United States))                (Asia/Shanghai timezone)
 3) [x] Installation source               4) [x] Software selection
        (Local media)                            (Minimal Install)
 5) [x] Installation Destination          6) [x] Kdump
        (Automatic partitioning                  (Kdump is enabled)
        selected)                         8) [!] Root password
 7) [ ] Network configuration                    (Password is not set.)
        (Not connected)
 9) [!] User creation
        (No user will be created)
  Please make your choice from above ['q' to quit | 'b' to begin installation |
  'r' to refresh]:

接下来我们要配置root密码

1
2
3
Please select new root password. You will have to type it twice.

Password:

输入你想要设置的密码(注意这里的输入不带回显的,放心输入)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Please select new root password. You will have to type it twice.

Password:
Password (confirm):
================================================================================
================================================================================
Question

The password you have provided is weak: The password fails the dictionary check
- it is based on a dictionary word.
Would you like to use it anyway?

Please respond 'yes' or 'no':

如果你设置的密码太过于简单,会提示你是否还需要使用,我这里只是创建模板简单一点方便后续的管理,像是生产环境推荐你设置一个更为复杂的密码。

在设置完成密码之后现在重新回到了主界面

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Installation

 1) [x] Language settings                 2) [x] Time settings
        (English (United States))                (Asia/Shanghai timezone)
 3) [x] Installation source               4) [x] Software selection
        (Local media)                            (Minimal Install)
 5) [x] Installation Destination          6) [x] Kdump
        (Automatic partitioning                  (Kdump is enabled)
        selected)                         8) [x] Root password
 7) [ ] Network configuration                    (Password is set.)
        (Not connected)
 9) [ ] User creation
        (No user will be created)
  Please make your choice from above ['q' to quit | 'b' to begin installation |
  'r' to refresh]:

现在输入b回车开始安装虚拟机。

在安装完成之后会输出如下

1
2
3
        Use of this product is subject to the license agreement found at /usr/share/centos-release/EULA

        Installation complete.  Press return to quit

提示已经安装完成,输入回车退出这个livecd

到这里虚拟机的安装就算是完成了。

虚拟机配置

在完成了虚拟机的安装之后我们还需要对虚拟机进行一些配置,比如说常用的包和网络设置。

在重启之后会到登陆的tty界面

1
2
3
4
CentOS Linux 7 (Core)
Kernel 3.10.0-1160.el7.x86_64 on an x86_64

localhost login:

输入设置好的用户名和密码登录

首先我们要设置一下网络

1
2
3
4
5
6
7
8
9
ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 52:54:00:03:8a:9d brd ff:ff:ff:ff:ff:ff

默认这个网卡是没有启动的,我们需要设置这个网卡开机自己启动。

1
2
nmcli con mod eth0 ipv4.method auto connection.autoconnect yes
nmcli con up eth0

为了能够正常的管理虚拟机的开关机,还必须要在虚拟机上安装ACPI服务

1
2
yum install -y acpid
systemctl enable acpid

安装bash补全

1
yum install -y bash-completion wget curl vim

创建一个ip.sh脚本:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/bin/bash

function set_ip(){
    nmcli con mod eth0 ipv4.method manual ipv4.addresses 192.168.122.$1/24 ipv4.dns "192.168.122.1 114.114.114.114" ipv4.gateway 192.168.122.1 connection.autoconnect yes
}


function apply_up(){
    nmcli con up eth0
}


set_ip $1
apply_up

关掉SSH的DNS检测:

1
vi /etc/ssh/sshd_config
1
UseDNS no

到这里虚拟机的设置已经完成了,让我们清理一下这个虚拟机。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
yum clean all
echo > /etc/machine-id
rm -f /etc/ssh/ssh_host
rm -rf /root/.ssh/
rm -f /root/anaconda-ks.cfg
rm -f /root/.bash_history
unset HISTFILE
rm -f /var/log/boot.log
rm -f /var/log/cron
rm -f /var/log/dmesg
rm -f /var/log/grubby
rm -f /var/log/lastlog
rm -f /var/log/maillog
rm -f /var/log/messages
rm -f /var/log/secure
rm -f /var/log/spooler
rm -f /var/log/tallylog
rm -f /var/log/wpa_supplicant.log
rm -f /var/log/wtmp
rm -f /var/log/yum.log
rm -f /var/log/audit/audit.log
rm -f /var/log/ovirt-guest-agent/ovirt-guest-agent.log
rm -f /var/log/tuned/tuned.log
sys-unconfig

执行完成命令后,我们的虚拟机模板也算是做好了。

Ubuntu Server 20.04

1
qemu-img create -f qcow2 workspace/qemu/disk/ubuntu20.04.qcow2 40G
1
2
3
4
5
6
7
8
9
sudo virt-install --virt-type=kvm \
--name=ubuntu20.04 \
--memory=2048 \
--vcpus=1 \
--cpu=host-passthrough \
--cdrom=workspace/qemu/iso/ubuntu-20.04.2-live-server-amd64.iso \
--file=workspace/qemu/disk/ubuntu20.04.qcow2,format=qcow2 \
--network network=default,model=virtio \
--graphics=vnc,password=000000,listen=0.0.0.0,port=5900

创建并编辑ip.sh,内容如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash

set -x 
cp -v /etc/netplan/00-installer-config.yaml /etc/netplan/00-installer-config.yaml.bak

cat >  /etc/netplan/00-installer-config.yaml << EOF
# This is the network config written by 'subiquity'
network:
  ethernets:
    enp1s0:
      dhcp4: no
      addresses: [192.168.122.$1/24]
      gateway4: 192.168.122.1
      nameservers:
        addresses: [192.168.122.1,114.114.114.114]
      optional: true
  version: 2
EOF
netplan apply

echo "all done!"

保存退出之后添加执行权限:

1
chmod +x ip.sh

修改sudo权限:

1
2
sudo vi /etc/sudoers
%admin ALL=(ALL:ALL) NOPASSWD: ALL

console配置:

修改 /etc/default/grub

1
2
3
4
5
6
7
## add:
GRUB_TERMINAL="console serial"
GRUB_SERIAL_COMMAND="serial --speed=115200"

## change:
# GRUB_CMDLINE_LINUX=""
GRUB_CMDLINE_LINUX="console=tty1 console=ttyS0,115200"

更新grub配置文件:

1
grub-mkconfig -o /boot/grub/grub.cfg

清理机器:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
apt-get autoremove
echo > /etc/machine-id
rm -f /etc/ssh/ssh_host
rm -rf /root/.ssh/
rm -f /root/.bash_history
unset HISTFILE
rm -f /var/log/boot.log
rm -f /var/log/cron
rm -f /var/log/dmesg*
rm -f /var/log/grubby
rm -f /var/log/lastlog
rm -f /var/log/maillog
rm -f /var/log/messages
rm -f /var/log/secure
rm -f /var/log/spooler
rm -f /var/log/tallylog
rm -f /var/log/wpa_supplicant.log
rm -f /var/log/wtmp
rm -f /var/log/apt/*
rm -f /var/log/audit/audit.log
rm -f /var/log/ovirt-guest-agent/ovirt-guest-agent.log
rm -f /var/log/tuned/tuned.log
shutdown -h now

编辑虚拟机

1
sudo virsh edit ubuntu20.04

删除vnc

KVM Windows 虚拟机

1
qemu-img create -f qcow2 workspace/qemu/disk/windows10.qcow2 80G

创建虚拟机:

1
2
3
4
5
6
7
8
9
sudo virt-install --virt-type=kvm \
--name=windows10 \
--memory=2048 \
--vcpus=2 \
--cpu=host-passthrough \
--file=workspace/qemu/disk/windows10.qcow2 \
--cdrom=workspace/qemu/iso/windows10.iso \
--network network=default,model=virtio \
--graphics=vnc,password=passwd,listen=0.0.0.0,port=5900

批量创建虚拟机的脚本

在没有开始设置terraform之类的工具之前,我们可以用一个简单的脚本来批量创建虚拟机

创建并编辑virt.sh文件

1
nano -w virt.sh

内容如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/bin/bash
HOSTLIST=`cat host`
TP_NAME=centos7
DISK_DIR=/home/yafa/workspace/qemu/disk

function _create_vm(){
	for host in ${HOSTLIST[@]}; do 
		sudo virt-clone -o $TP_NAME -n ${host}  -f $DISK_DIR/${host}.qcow2
done
}

	

function _start_vm(){
	for host in ${HOSTLIST[@]};do 
		sudo virsh start ${host} 
done
}

function _shutdown_vm(){
	for host in ${HOSTLIST[@]};do 
		sudo virsh shutdown ${host} 
done
}

function _remove_vm(){
	for host in ${HOSTLIST[@]};do 
		sudo virsh destroy ${host} 
done
	for host in ${HOSTLIST[@]};do 
		sudo virsh undefine ${host} 
done
	for host in ${HOSTLIST[@]};do 
		rm  -rf $DISK_DIR/${host}.qcow2
done
}


case $1 in
	start )
		_start_vm
		;;
	remove )
		_remove_vm
		;;
	create )
		_create_vm
		;;
	shutdown )
		_shutdown_vm
		;;
	* ) 
		echo "Please type start,remove,create!"
		;;
esac

用法 比如说我们想要创建三个机器,可以这样使用。 创建一个host的文件

1
echo -e "node1 \nnode2 \nnode3" > host

创建虚拟机

1
bash virt.sh create

输入如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
bash virt.sh create
Password:
Allocating 'node1.qcow2'                                                                                                |  10 GB  00:00:02

Clone 'node1' created successfully.
Allocating 'node2.qcow2'                                                                                                |  10 GB  00:00:03

Clone 'node2' created successfully.
Allocating 'node3.qcow2'                                                                                                |  10 GB  00:00:02

Clone 'node3' created successfully.

如果你觉得每次创建都需要输入密码不是很舒服可以配置一下sudo

创建并编辑/etc/sudoers.d/xena

1
nano -w /etc/sudoers.d/xena

内容如下

1
2
Cmnd_Alias        VM   =   /usr/bin/virt-install, /usr/bin/virsh, /usr/bin/virt-clone
xena	ALL=(ALL)	NOPASSWD: VM

保存退出之后在运行这个脚本就不用再手动输入密码了。

DNS 配置

DNS部分的配置可以参考我的这篇DNS服务器

XEN环境的安装和配置

Docker的安装和配置

参考资料

https://www.raymii.org/s/articles/virt-install_introduction_and_copy_paste_distro_install_commands.html

http://www.chenshake.com/automate-the-construction-of-a-linux-virtual-machine-mirror/