Windows下虚拟机的创建主要为VirtualBox和VMWare。本文采用VirtualBox搭建虚拟机,并使用Vagrant对虚拟机进行自动化管理,包括虚拟机的创建,虚拟机初始环境的自动化建设,也包括虚拟机和虚拟机环境重建,虚拟机的销毁等。

在Windows下运行虚拟机首先要确保计算机已经打开了CPU的虚拟机支持,现阶段的PC机CPU都包含对虚拟机的支持,包括Intel和AMD等,我们可以通过打开Windows任务管理器进行核查。

可以看到有一项:虚拟机:已启用,表征该PC机CPU的虚拟机支持功能已经开启,如若不是,则可进入PC机的BIOS开启CPU虚拟机的支持功能,具体操作随不同的PC机有一定的差别。

一 VirtualBox和Vagrant的安装

1 安装VirtualBox

进入Oracle VM VirtualBox网站网站下载Windows版VirtualBox 7.0.4 platform packages(https://download.virtualbox.org/virtualbox/7.0.4/VirtualBox-7.0.4-154605-Win.exe),以及VirtualBox 7.0.4 Oracle VM VirtualBox Extension Pack(https://download.virtualbox.org/virtualbox/7.0.4/Oracle_VM_VirtualBox_Extension_Pack-7.0.4.vbox-extpack),当前版是7.0.4。双击VirtualBox-7.0.4-154605-Win.exe。

2 安装Vagrant

进入Vagrant by HashiCorp (vagrantup.com)网站。下载下载Windows版Vagrant(https://releases.hashicorp.com/vagrant/2.3.3/vagrant_2.3.3_windows_amd64.msi)。双击vagrant_2.3.3_windows_amd64.msi。

在C:\下创建目录vagrant,将来所有vagrant相关命令执行和配置文件都在这一目录下。

cd c:\c:\>mkdir vagrantc:\>cd vagrantc:\vagrant>vagrant --version
Vagrant 2.3.3

下面我们用Vagrant创建、管理虚拟机。

二 使用Vagrant工具创建管理Windows虚拟机

Vagrant是实现虚拟机全生命周期管理的命令行工具。通过面向自动化和简单易用的工作流构建完整开发环境,降低开发环境配置时间,提升从开发到作业的效率,并做到在自己的机器上就能做到。

为什么使用 Vagrant

Vagrant 提供易于配置、可重现和便携的工作环境,该工作环境建立在行业标准技术之上,并由单一一致的工作流程控制,以帮助最大限度地提高您和您的团队的生产力和灵活性。 Vagrant 基于前辈的杰出工具,实现这样的超凡能力。可以在 VirtualBox、VMware、AWS 或任何其他提供商之上,并通过诸如 shell 脚本、Chef 或 Puppet 等行业标准配置工具,在虚拟机上自动安装和配置软件。

对于开发人员 如果您是开发人员,Vagrant 会将依赖项及其配置隔离在一个一次性的、一致的环境中,而不会牺牲您习惯使用的任何工具(编辑器、浏览器、调试器等)。 一旦您或其他人创建了一个 Vagrantfile,您只需要启动 vagrant up,一切都已安装和配置好供您使用。 您团队的其他成员从相同的配置创建他们的开发环境,因此无论您是在 Linux、Mac OS X 还是 Windows 上工作,您的所有团队成员都在相同的环境中运行代码,针对相同的依赖项,配置相同方法。 告别“只在我的机器上工作”问题。

对于运维人员 如果您是运维工程师或 DevOps 工程师,Vagrant 为您提供一次性环境和一致的工作流程,用于开发和测试基础架构管理脚本。 您可以使用 VirtualBox 或 VMware 等本地虚拟化快速测试 shell 脚本、Chef Cookbooks、Puppet 模块等。 然后,使用相同的配置,您可以使用相同的工作流程在 AWS 或 RackSpace 等远程云上测试这些脚本。 抛弃您的自定义脚本以回收 EC2 实例,停止向各种机器发送 SSH 提示,并开始使用 Vagrant 让您的生活变得理智。

对于设计师 如果你是一名设计师,Vagrant 会自动设置网络应用程序所需的一切,以便你专注于做你最擅长的事情:设计。 一旦开发人员配置了 Vagrant,您就无需担心如何让该应用程序再次运行。 无需再麻烦其他开发人员来帮助您修复环境以便您可以测试设计。 只需检查代码,vagrant up,然后开始设计。

对于每个人 Vagrant 是为每个人设计的,作为创建虚拟化环境的最简单和最快的方法!

下面测试创建一个Almalinux虚拟机。

在C:\vagrant目录创建vagrantfile。

Vagrant.configure("2") do |config|config.vm.box = "bento/almalinux-9"
end
c:\vagrant>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'bento/almalinux-9' could not be found. Attempting to find and install...default: Box Provider: virtualboxdefault: Box Version: >= 0
==> default: Loading metadata for box 'bento/almalinux-9'default: URL: https://vagrantcloud.com/bento/almalinux-9
==> default: Adding box 'bento/almalinux-9' (v202206.14.0) for provider: virtualboxdefault: Downloading: https://vagrantcloud.com/bento/boxes/almalinux-9/versions/202206.14.0/providers/virtualbox.boxdefault:
==> default: Successfully added box 'bento/almalinux-9' (v202206.14.0) for 'virtualbox'!
==> default: Importing base box 'bento/almalinux-9'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'bento/almalinux-9' version '202206.14.0' is up to date...
==> default: Setting the name of the VM: vagrant_default_1670130919760_44251
Vagrant is currently configured to create VirtualBox synced folders with
the `SharedFoldersEnableSymlinksCreate` option enabled. If the Vagrant
guest is not trusted, you may want to disable this option. For more
information on this option, please refer to the VirtualBox manual:https://www.virtualbox.org/manual/ch04.html#sharedfoldersThis option can be disabled globally with an environment variable:VAGRANT_DISABLE_VBOXSYMLINKCREATE=1or on a per folder basis within the Vagrantfile:config.vm.synced_folder '/host/path', '/guest/path', SharedFoldersEnableSymlinksCreate: false
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...default: Adapter 1: nat
==> default: Forwarding ports...default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...default: SSH address: 127.0.0.1:2222default: SSH username: vagrantdefault: SSH auth method: private keydefault:default: Vagrant insecure key detected. Vagrant will automatically replacedefault: this with a newly generated keypair for better security.default:default: Inserting generated public key within guest...default: Removing insecure key from the guest if it's present...default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...default: The guest additions on this VM do not match the installed version ofdefault: VirtualBox! In most cases this is fine, but in rare cases it candefault: prevent things such as shared folders from working properly. If you seedefault: shared folder errors, please make sure the guest additions within thedefault: virtual machine match the version of VirtualBox you have installed ondefault: your host and reload your VM.default:default: Guest Additions Version: 6.1.34default: VirtualBox Version: 7.0
==> default: Mounting shared folders...default: /vagrant => C:/vagrant

从VirtualBox虚拟机管理器可以看到创建的虚拟机已经运行。

通过vagrant ssh可以连接到虚拟机。

c:\vagrant>vagrant sshThis system is built by the Bento project by Chef Software
More information can be found at https://github.com/chef/bento
[vagrant@localhost ~]$ ls
[vagrant@localhost ~]$ ls /
afs  bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  vagrant  var
[vagrant@localhost ~]$

也可以通过MobaXterm通过端口2222连接。缺省用户名和密码:vagrant:vagrant。

可以事先将almalinux-9虚拟机镜像(box)从以下地址下载下来:https://app.vagrantup.com/bento/boxes/almalinux-9/versions/202208.18/providers/virtualbox.box

执行vagrant box add:

c:\vagrant>vagrant box add --name almalinux-9 ./almalinux-9.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'almalinux' (v0) for provider:box: Unpacking necessary files from: file://c:/vagrant/almalinux-9.boxbox:
==> box: Successfully added box 'almalinux' (v0) for 'virtualbox'!c:\vagrant>vagrant box list
almalinux-9         (virtualbox, 0)

修改vagrantfile:

Vagrant.configure("2") do |config|config.vm.box = "almalinux-9"
end

从环境中移除box:

c:\vagrant>vagrant box remove almalinux-9
Removing box 'almalinux-9' (v0) with provider 'virtualbox'...c:\vagrant>vagrant box list

我们可以看到Vagrant创建虚机机的同时,还为我们创建了一个共享目录/vagrant => C:/vagrant,将Windows主机的C:\vagrant同虚拟机/vagrant目录同步,方便虚拟机和Windows主机文件共享。

运行的虚拟机通过以下命令操作而进入不同的状态。

vagrant destroy         停止并销毁虚拟机,一般使用vagrant destroy -f强制停止并销毁虚拟机
vagrant halt            停止虚拟机
vagrant reload          重启虚拟机
vagrant suspend         虚拟机挂起
vagrant resume          重新运行虚拟机
vagrant up              使用vagrantfile配置启动虚拟机

三 一步创建多台虚拟机

通过vagrantfile配置,能够一次性创建运行多台虚拟机。让我们修改vagrantfile。

Vagrant.configure("2") do |config|config.vm.provider "virtualbox" do |vb|# Display the VirtualBox GUI when booting the machine#vb.gui = true# Customize the amount of memory on the VM:vb.memory = "1024"# Customize the CPUs used:vb.cpus = 2end(1..2).each do |i|config.vm.define "node0#{i}" do |node|node.vm.box = "bento/almalinux-9"node.vm.hostname = "node0#{i}"node.vm.network "private_network", ip: "192.168.99.1#{i}"node.vm.synced_folder "share/", "/home/vagrant/share"endend
end

c:\vagrant>vagrant destroy -f
==> node02: Discarding saved state of VM...
==> node02: Destroying VM and associated drives...
==> node01: Discarding saved state of VM...
==> node01: Destroying VM and associated drives...

四 为虚拟机安装和配置基础应用及环境

通过Vagrant provision可以为运行的虚拟机安装与配置基础环境。

创建entry point.sh。

#!/bin/bashsudo dnf install -y wget vim less expectsudo sed -i 's/^#\(PubkeyAuthentication yes\)/\1/' /etc/ssh/sshd_config
sudo sed -i 's/^#\(PermitRootLogin\) .*/\1 yes/' /etc/ssh/sshd_config
echo "StrictHostKeyChecking no" | sudo tee -a /etc/ssh/ssh_config
ssh-keygen -t rsa -f /home/vagrant/.ssh/id_rsa -P ''
sudo chown -R vagrant:vagrant /home/vagrant/.ssh
#sudo cat /home/vagrant/.ssh/id_rsa.pub >> /home/vagrant/.ssh/authorized_keyscp /vagrant/sshpub.sh /home/vagrant/
cp /vagrant/hosts.txt /home/vagrant/cat /home/vagrant/hosts.txt | sudo tee -a /etc/hosts

文件hosts.txt保存分配IP地址与虚拟机主机名的对应关系。

192.168.99.11 node01
192.168.99.12 node02

修改vagrantfile。

Vagrant.configure("2") do |config|config.vm.provider "virtualbox" do |vb|# Display the VirtualBox GUI when booting the machine#vb.gui = true# Customize the amount of memory on the VM:vb.memory = "1024"# Customize the CPUs used:vb.cpus = 2end(1..2).each do |i|config.vm.define "node0#{i}" do |node|node.vm.box = "bento/almalinux-9"node.vm.hostname = "node0#{i}"node.vm.network "private_network", ip: "192.168.99.1#{i}"node.vm.synced_folder "share/", "/home/vagrant/share"endendconfig.vm.provision "shell", path: "entrypoint.sh"end
c:\vagrant>vagrant up
Bringing machine 'node01' up with 'virtualbox' provider...
Bringing machine 'node02' up with 'virtualbox' provider...
==> node01: Importing base box 'bento/almalinux-9'...
==> node01: Matching MAC address for NAT networking...
==> node01: Checking if box 'bento/almalinux-9' version '202206.14.0' is up to date...
==> node01: Setting the name of the VM: vagrant_node01_1670154889848_31388
==> node01: Clearing any previously set network interfaces...
==> node01: Preparing network interfaces based on configuration...node01: Adapter 1: natnode01: Adapter 2: hostonly
==> node01: Forwarding ports...node01: 22 (guest) => 2222 (host) (adapter 1)
==> node01: Running 'pre-boot' VM customizations...
==> node01: Booting VM...
==> node01: Waiting for machine to boot. This may take a few minutes...node01: SSH address: 127.0.0.1:2222node01: SSH username: vagrantnode01: SSH auth method: private keynode01:node01: Vagrant insecure key detected. Vagrant will automatically replacenode01: this with a newly generated keypair for better security.node01:node01: Inserting generated public key within guest...node01: Removing insecure key from the guest if it's present...node01: Key inserted! Disconnecting and reconnecting using new SSH key...
==> node01: Machine booted and ready!
==> node01: Checking for guest additions in VM...node01: The guest additions on this VM do not match the installed version ofnode01: VirtualBox! In most cases this is fine, but in rare cases it cannode01: prevent things such as shared folders from working properly. If you seenode01: shared folder errors, please make sure the guest additions within thenode01: virtual machine match the version of VirtualBox you have installed onnode01: your host and reload your VM.node01:node01: Guest Additions Version: 6.1.34node01: VirtualBox Version: 7.0
==> node01: Setting hostname...
==> node01: Configuring and enabling network interfaces...
==> node01: Mounting shared folders...node01: /vagrant => C:/vagrantnode01: /home/vagrant/share => C:/vagrant/share
==> node01: Running provisioner: shell...node01: Running: C:/Users/lugng/AppData/Local/Temp/vagrant-shell20221204-9852-up0nvu.shnode01: AlmaLinux 9 - AppStream                         1.7 MB/s | 7.0 MB     00:04node01: AlmaLinux 9 - BaseOS                            730 kB/s | 2.0 MB     00:02node01: AlmaLinux 9 - Extras                            1.3 kB/s |  17 kB     00:12node01: Last metadata expiration check: 0:00:01 ago on Sun 04 Dec 2022 11:56:05 AM UTC.node01: Package wget-1.21.1-7.el9.x86_64 is already installed.node01: Package less-590-1.el9_0.x86_64 is already installed.node01: Dependencies resolved.node01: ================================================================================node01:  Package            Arch       Version                      Repository     Sizenode01: ================================================================================node01: Installing:node01:  expect             x86_64     5.45.4-15.el9                appstream     246 knode01:  vim-enhanced       x86_64     2:8.2.2637-16.el9_0.3        appstream     1.8 Mnode01: Installing dependencies:node01:  gpm-libs           x86_64     1.20.7-29.el9                appstream      20 knode01:  tcl                x86_64     1:8.6.10-7.el9               baseos        1.1 Mnode01:  vim-common         x86_64     2:8.2.2637-16.el9_0.3        appstream     6.6 Mnode01:  vim-filesystem     noarch     2:8.2.2637-16.el9_0.3        baseos         20 knode01:node01: Transaction Summarynode01: ================================================================================node01: Install  6 Packagesnode01:node01: Total download size: 9.7 Mnode01: Installed size: 39 Mnode01: Downloading Packages:node01: (1/6): gpm-libs-1.20.7-29.el9.x86_64.rpm         56 kB/s |  20 kB     00:00node01: (2/6): expect-5.45.4-15.el9.x86_64.rpm          380 kB/s | 246 kB     00:00node01: (3/6): tcl-8.6.10-7.el9.x86_64.rpm              1.1 MB/s | 1.1 MB     00:00node01: (4/6): vim-filesystem-8.2.2637-16.el9_0.3.noarc 161 kB/s |  20 kB     00:00node01: (5/6): vim-enhanced-8.2.2637-16.el9_0.3.x86_64. 859 kB/s | 1.8 MB     00:02node01: (6/6): vim-common-8.2.2637-16.el9_0.3.x86_64.rp 1.8 MB/s | 6.6 MB     00:03node01: --------------------------------------------------------------------------------node01: Total                                           935 kB/s | 9.7 MB     00:10node01: Running transaction checknode01: Transaction check succeeded.node01: Running transaction testnode01: Transaction test succeeded.node01: Running transactionnode01:   Preparing        :                                                        1/1node01:   Installing       : vim-filesystem-2:8.2.2637-16.el9_0.3.noarch            1/6node01:   Installing       : vim-common-2:8.2.2637-16.el9_0.3.x86_64                2/6node01:   Installing       : tcl-1:8.6.10-7.el9.x86_64                              3/6node01:   Installing       : gpm-libs-1.20.7-29.el9.x86_64                          4/6node01:   Installing       : vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64              5/6node01:   Installing       : expect-5.45.4-15.el9.x86_64                            6/6node01:   Running scriptlet: expect-5.45.4-15.el9.x86_64                            6/6node01:   Verifying        : expect-5.45.4-15.el9.x86_64                            1/6node01:   Verifying        : gpm-libs-1.20.7-29.el9.x86_64                          2/6node01:   Verifying        : vim-common-2:8.2.2637-16.el9_0.3.x86_64                3/6node01:   Verifying        : vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64              4/6node01:   Verifying        : tcl-1:8.6.10-7.el9.x86_64                              5/6node01:   Verifying        : vim-filesystem-2:8.2.2637-16.el9_0.3.noarch            6/6node01:node01: Installed:node01:   expect-5.45.4-15.el9.x86_64node01:   gpm-libs-1.20.7-29.el9.x86_64node01:   tcl-1:8.6.10-7.el9.x86_64node01:   vim-common-2:8.2.2637-16.el9_0.3.x86_64node01:   vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64node01:   vim-filesystem-2:8.2.2637-16.el9_0.3.noarchnode01:node01: Complete!node01: StrictHostKeyChecking nonode01: Generating public/private rsa key pair.node01: Your identification has been saved in /home/vagrant/.ssh/id_rsanode01: Your public key has been saved in /home/vagrant/.ssh/id_rsa.pubnode01: The key fingerprint is:node01: SHA256:PPjIrHiv8L7stBdHOSXdsr6d5XQzOGwZNBnGcl73+Tw root@node01node01: The key's randomart image is:node01: +---[RSA 3072]----+node01: |         . ..oo  |node01: |        . +.o* ..|node01: |         + o= o +|node01: |       o+ .  o ..|node01: |      ..So  . +..|node01: |     o.o...  *oE+|node01: |  . . +o.  o.=..+|node01: |   *.o.   . o .  |node01: |  .+X=.          |node01: +----[SHA256]-----+node01: 192.168.99.11 node01node01: 192.168.99.12 node02
==> node01: Running action triggers after up ...
==> node01: Running trigger: trigger...
==> node01: Running a trigger after VMs up!
==> node02: Importing base box 'bento/almalinux-9'...
==> node02: Matching MAC address for NAT networking...
==> node02: Checking if box 'bento/almalinux-9' version '202206.14.0' is up to date...
==> node02: Setting the name of the VM: vagrant_node02_1670155002843_67922
==> node02: Fixed port collision for 22 => 2222. Now on port 2200.
==> node02: Clearing any previously set network interfaces...
==> node02: Preparing network interfaces based on configuration...node02: Adapter 1: natnode02: Adapter 2: hostonly
==> node02: Forwarding ports...node02: 22 (guest) => 2200 (host) (adapter 1)
==> node02: Running 'pre-boot' VM customizations...
==> node02: Booting VM...
==> node02: Waiting for machine to boot. This may take a few minutes...node02: SSH address: 127.0.0.1:2200node02: SSH username: vagrantnode02: SSH auth method: private keynode02:node02: Vagrant insecure key detected. Vagrant will automatically replacenode02: this with a newly generated keypair for better security.node02:node02: Inserting generated public key within guest...node02: Removing insecure key from the guest if it's present...node02: Key inserted! Disconnecting and reconnecting using new SSH key...
==> node02: Machine booted and ready!
==> node02: Checking for guest additions in VM...node02: The guest additions on this VM do not match the installed version ofnode02: VirtualBox! In most cases this is fine, but in rare cases it cannode02: prevent things such as shared folders from working properly. If you seenode02: shared folder errors, please make sure the guest additions within thenode02: virtual machine match the version of VirtualBox you have installed onnode02: your host and reload your VM.node02:node02: Guest Additions Version: 6.1.34node02: VirtualBox Version: 7.0
==> node02: Setting hostname...
==> node02: Configuring and enabling network interfaces...
==> node02: Mounting shared folders...node02: /vagrant => C:/vagrantnode02: /home/vagrant/share => C:/vagrant/share
==> node02: Running provisioner: shell...node02: Running: C:/Users/lugng/AppData/Local/Temp/vagrant-shell20221204-9852-y6myp9.shnode02: AlmaLinux 9 - AppStream                         1.4 MB/s | 7.0 MB     00:04node02: AlmaLinux 9 - BaseOS                            688 kB/s | 2.0 MB     00:02node02: AlmaLinux 9 - Extras                            8.3 kB/s |  17 kB     00:01node02: Package wget-1.21.1-7.el9.x86_64 is already installed.node02: Package less-590-1.el9_0.x86_64 is already installed.node02: Dependencies resolved.node02: ================================================================================node02:  Package            Arch       Version                      Repository     Sizenode02: ================================================================================node02: Installing:node02:  expect             x86_64     5.45.4-15.el9                appstream     246 knode02:  vim-enhanced       x86_64     2:8.2.2637-16.el9_0.3        appstream     1.8 Mnode02: Installing dependencies:node02:  gpm-libs           x86_64     1.20.7-29.el9                appstream      20 knode02:  tcl                x86_64     1:8.6.10-7.el9               baseos        1.1 Mnode02:  vim-common         x86_64     2:8.2.2637-16.el9_0.3        appstream     6.6 Mnode02:  vim-filesystem     noarch     2:8.2.2637-16.el9_0.3        baseos         20 knode02:node02: Transaction Summarynode02: ================================================================================node02: Install  6 Packagesnode02:node02: Total download size: 9.7 Mnode02: Installed size: 39 Mnode02: Downloading Packages:node02: (1/6): gpm-libs-1.20.7-29.el9.x86_64.rpm         52 kB/s |  20 kB     00:00node02: (2/6): expect-5.45.4-15.el9.x86_64.rpm          372 kB/s | 246 kB     00:00node02: (3/6): tcl-8.6.10-7.el9.x86_64.rpm              991 kB/s | 1.1 MB     00:01node02: (4/6): vim-filesystem-8.2.2637-16.el9_0.3.noarc 128 kB/s |  20 kB     00:00node02: (5/6): vim-enhanced-8.2.2637-16.el9_0.3.x86_64. 993 kB/s | 1.8 MB     00:01node02: (6/6): vim-common-8.2.2637-16.el9_0.3.x86_64.rp 1.4 MB/s | 6.6 MB     00:04node02: --------------------------------------------------------------------------------node02: Total                                           1.2 MB/s | 9.7 MB     00:07node02: Running transaction checknode02: Transaction check succeeded.node02: Running transaction testnode02: Transaction test succeeded.node02: Running transactionnode02:   Preparing        :                                                        1/1node02:   Installing       : vim-filesystem-2:8.2.2637-16.el9_0.3.noarch            1/6node02:   Installing       : vim-common-2:8.2.2637-16.el9_0.3.x86_64                2/6node02:   Installing       : tcl-1:8.6.10-7.el9.x86_64                              3/6node02:   Installing       : gpm-libs-1.20.7-29.el9.x86_64                          4/6node02:   Installing       : vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64              5/6node02:   Installing       : expect-5.45.4-15.el9.x86_64                            6/6node02:   Running scriptlet: expect-5.45.4-15.el9.x86_64                            6/6node02:   Verifying        : expect-5.45.4-15.el9.x86_64                            1/6node02:   Verifying        : gpm-libs-1.20.7-29.el9.x86_64                          2/6node02:   Verifying        : vim-common-2:8.2.2637-16.el9_0.3.x86_64                3/6node02:   Verifying        : vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64              4/6node02:   Verifying        : tcl-1:8.6.10-7.el9.x86_64                              5/6node02:   Verifying        : vim-filesystem-2:8.2.2637-16.el9_0.3.noarch            6/6node02:node02: Installed:node02:   expect-5.45.4-15.el9.x86_64node02:   gpm-libs-1.20.7-29.el9.x86_64node02:   tcl-1:8.6.10-7.el9.x86_64node02:   vim-common-2:8.2.2637-16.el9_0.3.x86_64node02:   vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64node02:   vim-filesystem-2:8.2.2637-16.el9_0.3.noarchnode02:node02: Complete!node02: StrictHostKeyChecking nonode02: Generating public/private rsa key pair.node02: Your identification has been saved in /home/vagrant/.ssh/id_rsanode02: Your public key has been saved in /home/vagrant/.ssh/id_rsa.pubnode02: The key fingerprint is:node02: SHA256:s9H1SMf4cKCguICPZt/p1b3lVow4/RvVZ62qgNkf+u4 root@node02node02: The key's randomart image is:node02: +---[RSA 3072]----+node02: |        .   .    |node02: | .   . . . . +   |node02: |. . . .   . = +  |node02: | o . .   . o B  o|node02: |.o. .   S . + = *|node02: |o . . .+.+.o o =o|node02: |   . oo.+.....+. |node02: |    . .  + .+o ..|node02: |     .  .+Eoo. ..|node02: +----[SHA256]-----+node02: 192.168.99.11 node01node02: 192.168.99.12 node02
==> node02: Running action triggers after up ...
==> node02: Running trigger: trigger...
==> node02: Running a trigger after VMs up!

五 利用Vagrant trigger实现虚拟机之间的免密登录

定义在虚拟机启动后,通过循环SSH登录彼此,执行ssh-copy-id,实现虚拟机间相互免密登录。

创建虚拟机彼此循环登录的shell脚本,sshloginset.sh。

#!/bin/bash
set -e# 取得集群的所有主机名,这里需要注意:hosts配置的IP和主机名只能用一个空格分割
# tail -n +2 表示从第2行开始
# cut -d ' ' -f 2 表示用空格分割每一行并获取第2列
hostList=$(cat /home/vagrant/hosts.txt | tail -n +1 | cut -d ' ' -f 2)#服务器和命令设置
user=vagrant
passwd=vagrant
cmd=/home/vagrant/sshcpid.sh#ssh登录函数
sshlgset(){echo "======>$host ssh in..."/usr/bin/expect <<EOFspawn ssh $user@$host $cmdexpect {#    "*yes/no*" {send "yes\r" ; exp_continue}"*password*" {send "$passwd\r" ; exp_continue}}EOF
}set timeout 30
for host in $hostList
dosshlgset
donewait

创建虚拟机彼此ssh-copy-id shell脚本。sshcpid.sh。

#!/bin/bash
set -e# 取得集群的所有主机名,这里需要注意:hosts配置的IP和主机名只能用一个空格分割
# tail -n +2 表示从第2行开始
# cut -d ' ' -f 2 表示用空格分割每一行并获取第2列
hostList=$(cat /home/vagrant/hosts.txt | tail -n +1 | cut -d ' ' -f 2)
logPre=PPK#服务器密码
user=vagrant
passwd=vagrant#拷贝公钥函数
sshcopyid(){echo "======>$host ssh-copy-id..."/usr/bin/expect <<EOFspawn ssh-copy-id $user@$hostexpect {#    "*yes/no*" {send "yes\r" ; exp_continue}"*password*" {send "$passwd\r" ; exp_continue}}EOF
}set timeout 15
for host in $hostList
dosshcopyid
donewait

修改vagrantfile,添加trigger代码段。

Vagrant.configure("2") do |config|config.vm.provider "virtualbox" do |vb|# Display the VirtualBox GUI when booting the machine#vb.gui = true# Customize the amount of memory on the VM:vb.memory = "1024"# Customize the CPUs used:vb.cpus = 2end(1..2).each do |i|config.vm.define "node0#{i}" do |node|node.vm.box = "bento/almalinux-9"node.vm.hostname = "node0#{i}"node.vm.network "private_network", ip: "192.168.99.1#{i}"node.vm.synced_folder "share/", "/home/vagrant/share"endendconfig.vm.provision "shell", path: "entrypoint.sh"config.trigger.after :up do |trigger|trigger.name = "trigger"trigger.info = "Running a trigger after VMs up!"trigger.only_on = "node02"trigger.run_remote = {path: "sshloginset.sh"}end
end

运行。

c:\vagrant>vagrant up
Bringing machine 'node01' up with 'virtualbox' provider...
Bringing machine 'node02' up with 'virtualbox' provider...
...
...
...
==> node02: Running action triggers after up ...
==> node02: Running trigger: trigger...
==> node02: Running a trigger after VMs up!node02: Running: C:/Users/lugng/AppData/Local/Temp/vagrant-shell20221205-5208-al4av6.shnode02: ======>node01 ssh in...node02: spawn ssh vagrant@node01 /home/vagrant/sshcpid.shnode02: Warning: Permanently added 'node01' (ED25519) to the list of known hosts.
vagrant@node01's password:node02: ======>node01 ssh-copy-id... \nnode02: spawn ssh-copy-id vagrant@node01node02: /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/vagrant/.ssh/id_rsa.pub"node02: /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installednode02: /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
vagrant@node01's password: vagrantnode02:node02:node02: Number of key(s) added: 1node02:node02: Now try logging into the machine, with:   "ssh 'vagrant@node01'"node02: and check to make sure that only the key(s) you wanted were added.node02:node02: ======>node02 ssh-copy-id... \nnode02: spawn ssh-copy-id vagrant@node02node02: /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/vagrant/.ssh/id_rsa.pub"node02: /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installednode02: /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
vagrant@node02's password: vagrantnode02:node02:node02: Number of key(s) added: 1node02:node02: Now try logging into the machine, with:   "ssh 'vagrant@node02'"node02: and check to make sure that only the key(s) you wanted were added.node02:node02: ======>node02 ssh in...node02: spawn ssh vagrant@node02 /home/vagrant/sshcpid.shnode02: Warning: Permanently added 'node02' (ED25519) to the list of known hosts.
vagrant@node02's password:node02: ======>node01 ssh-copy-id... \nnode02: spawn ssh-copy-id vagrant@node01node02: /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/vagrant/.ssh/id_rsa.pub"node02: /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installednode02: /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
vagrant@node01's password: vagrantnode02:node02:node02: Number of key(s) added: 1node02:node02: Now try logging into the machine, with:   "ssh 'vagrant@node01'"node02: and check to make sure that only the key(s) you wanted were added.node02:node02: ======>node02 ssh-copy-id... \nnode02: spawn ssh-copy-id vagrant@node02node02: /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/vagrant/.ssh/id_rsa.pub"node02: /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installednode02: /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
vagrant@node02's password: vagrantnode02:node02:node02: Number of key(s) added: 1node02:node02: Now try logging into the machine, with:   "ssh 'vagrant@node02'"node02: and check to make sure that only the key(s) you wanted were added.node02:

登录node01查看~/.ssh/authorized_keys。

可以看到node01和node02两台机器的公匙,表明这两台机器能够免密登录了。

Windows下虚拟机的自动化管理相关推荐

  1. Windows 下使用 SNMP 来管理网络

    本文介绍了 SNMP 协议 的基本概念,SNMP 的作用,以及如何在 Windows 下使用 SNMP 来管理网络中的设备. SNMP 的介绍 SNMP(Simple Network Manageme ...

  2. 19秋计算机应用基础在线作业2,计算机应用基础19秋在线作业2 Windows 下能浏览并管理文件 驱动器及网络连接的强大工具是...

    1.Evaluation Warning: The document was created with Spire.Doc for .NET.计算机应用基础19秋在线作业21 单选题1 Windows ...

  3. Windows下的多桌面管理器

    Microsoft公司提供了在Windows下的多桌面管理器,羡慕Linux的多桌面的同学们,可以一试. 这个多桌面管理器是作为 Windows PowerToys 的一部分,放在微软网站上的. go ...

  4. Windows下虚拟机安装Mac OS X ----- VM12安装Mac OS X 10.11

    Windows下虚拟机安装Mac OS X -– VM12安装Mac OS X 10.11 随着Iphone在国内大行其道,越来越多的开发者涌入IOS开发大军 中,但都苦于没有苹果机,本文即将介绍WI ...

  5. Windows下强大的包管理器(一)

    Windows下强大的包管理器Winget BB Time 官方解释 安装教程 Microsoft Store Github 使用教程 配置教程 彩虹进度条配置 未完待续... BB Time 我之前 ...

  6. 怎么把linux虚拟机硬盘扩容,Windows下虚拟机Linux(CentOS8)扩容设置 - 磁盘扩容中的坑和解决方法...

    摘要:[原创]转载请注明作者Johnthegreat和本文链接 由于虚拟机空间不足,为了避免重装虚拟机,做了一次无损扩容. 过程中的报错如下: 为了详细记录,这里将整个过程详述如下: 一.问题和需求 ...

  7. Windows下安装Vim插件管理Vundle

    VIM是编辑器之神,这个就不用说了,越使用越会体会到VIM的强大与便利.但是它的强大建立在众多插件组合之上,而Vim本身缺乏对插件的有效管理,安装插件并配置_vimrc文件非常不便.gmarik受到R ...

  8. 快速搭建自己的直播服务器,完成属于你的直播服务。(以windows 下虚拟机centos为例,对安装步骤进行详细说明)

    本文以srs v2.0-r8  安装为例,对搭建直播服务器的搭建和安装过程中的注意事项,进行详细的说明. 点击跳转到 教程原文 1.Windows下安装linux centos系统,版本建议 5.7- ...

  9. linux 虚拟机直播网站,快速搭建自己的直播服务器,完成属于你的直播服务。(以windows 下虚拟机centos为例,对安装步骤进行详细说明)...

    本文以srs v2.0-r8  安装为例,对搭建直播服务器的搭建和安装过程中的注意事项,进行详细的说明. 点击跳转到 教程原文 1.Windows下安装linux centos系统,版本建议 5.7- ...

最新文章

  1. 【MySQL】MySQL的group_concat使用例子
  2. 作者:刘新海(1976-),男,中国人民银行征信中心副研究员
  3. leetcode刷题:二叉树的中序遍历
  4. Elasticsearch基础(五)搜索匹配
  5. linux下vlc视频录制,使用VLC录制屏幕
  6. C#基础知识之读取xlsx文件Excel2007
  7. 纪念我的第一次面试——华为研发类面试
  8. Linux设置 鼠标滚轮方向,如何在Ubuntu中反转鼠标滚动方向(又名自然滚动) | MOS86...
  9. 大脸猫:「网站优化」网站优化宝典-网站优化建议
  10. Quartz 任务调度全攻略【转】
  11. 单词学习-Unit8Text3-2(15年7月30日,第9天)
  12. 单源最短路径: 差分约束和最短路径
  13. 《区块链技术原理与应用实践》新书面世 描绘数字经济全景新时代
  14. matlab 怎么嵌套循环,Matlab嵌套循环
  15. Linux文件系统类型
  16. 【硬件】美光DDR上丝印和型号对应关系
  17. 王者荣耀英雄简介-2
  18. 19.2、Javaweb案例_Servlet代码抽取优化分页数据redis缓存优化分页数据展示
  19. 用react模仿知乎的用户头像裁剪组件
  20. Unity常用模块设计 : Unity游戏排行榜的制作与优化

热门文章

  1. NtCreateFile获得的设备句柄为什么指向文件对象
  2. 数学建模比赛的经验帖
  3. 在n个球中,任意取出m个(不放回),求有多少种不同取法。(递归学习)
  4. C语言实现学生成绩管理系统(原码)
  5. SUPERBIN技术周刊第8期
  6. BZOJ4291: [PA2015]Kieszonkowe
  7. iPhone下旋转UIImage
  8. Scala基础教程--18--集合(二)
  9. 分布式集群架构解决方案
  10. LINUX_常用命令讲解