Windows下虚拟机的自动化管理-创新互联-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

Windows下虚拟机的自动化管理-创新互联

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

创新互联建站于2013年创立,是专业互联网技术服务公司,拥有项目成都网站制作、做网站、外贸营销网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元乐都做网站,已为上家服务,为乐都各地企业和个人服务,联系电话:028-86922220

在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 vagrant

c:\>cd vagrant

c:\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: virtualbox
    default: 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: virtualbox
    default: Downloading: https://vagrantcloud.com/bento/boxes/almalinux-9/versions/202206.14.0/providers/virtualbox.box
    default:
==>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#sharedfolders

This option can be disabled globally with an environment variable:

  VAGRANT_DISABLE_VBOXSYMLINKCREATE=1

or 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:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default:
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: 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 of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default:
    default: Guest Additions Version: 6.1.34
    default: VirtualBox Version: 7.0
==>default: Mounting shared folders...
    default: /vagrant =>C:/vagrant

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

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

c:\vagrant>vagrant ssh

This 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.box
    box:
==>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 = 2
  end
  
  (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"
	  end
	end
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/bash

sudo dnf install -y wget vim less expect

sudo 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_keys

cp /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 = 2
  end
  
  (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"
	  end
	end
	config.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: nat
    node01: 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:2222
    node01: SSH username: vagrant
    node01: SSH auth method: private key
    node01:
    node01: Vagrant insecure key detected. Vagrant will automatically replace
    node01: 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 of
    node01: VirtualBox! In most cases this is fine, but in rare cases it can
    node01: prevent things such as shared folders from working properly. If you see
    node01: shared folder errors, please make sure the guest additions within the
    node01: virtual machine match the version of VirtualBox you have installed on
    node01: your host and reload your VM.
    node01:
    node01: Guest Additions Version: 6.1.34
    node01: VirtualBox Version: 7.0
==>node01: Setting hostname...
==>node01: Configuring and enabling network interfaces...
==>node01: Mounting shared folders...
    node01: /vagrant =>C:/vagrant
    node01: /home/vagrant/share =>C:/vagrant/share
==>node01: Running provisioner: shell...
    node01: Running: C:/Users/lugng/AppData/Local/Temp/vagrant-shell20221204-9852-up0nvu.sh
    node01: AlmaLinux 9 - AppStream                         1.7 MB/s | 7.0 MB     00:04
    node01: AlmaLinux 9 - BaseOS                            730 kB/s | 2.0 MB     00:02
    node01: AlmaLinux 9 - Extras                            1.3 kB/s |  17 kB     00:12
    node01: 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     Size
    node01: ================================================================================
    node01: Installing:
    node01:  expect             x86_64     5.45.4-15.el9                appstream     246 k
    node01:  vim-enhanced       x86_64     2:8.2.2637-16.el9_0.3        appstream     1.8 M
    node01: Installing dependencies:
    node01:  gpm-libs           x86_64     1.20.7-29.el9                appstream      20 k
    node01:  tcl                x86_64     1:8.6.10-7.el9               baseos        1.1 M
    node01:  vim-common         x86_64     2:8.2.2637-16.el9_0.3        appstream     6.6 M
    node01:  vim-filesystem     noarch     2:8.2.2637-16.el9_0.3        baseos         20 k
    node01:
    node01: Transaction Summary
    node01: ================================================================================
    node01: Install  6 Packages
    node01:
    node01: Total download size: 9.7 M
    node01: Installed size: 39 M
    node01: Downloading Packages:
    node01: (1/6): gpm-libs-1.20.7-29.el9.x86_64.rpm         56 kB/s |  20 kB     00:00
    node01: (2/6): expect-5.45.4-15.el9.x86_64.rpm          380 kB/s | 246 kB     00:00
    node01: (3/6): tcl-8.6.10-7.el9.x86_64.rpm              1.1 MB/s | 1.1 MB     00:00
    node01: (4/6): vim-filesystem-8.2.2637-16.el9_0.3.noarc 161 kB/s |  20 kB     00:00
    node01: (5/6): vim-enhanced-8.2.2637-16.el9_0.3.x86_64. 859 kB/s | 1.8 MB     00:02
    node01: (6/6): vim-common-8.2.2637-16.el9_0.3.x86_64.rp 1.8 MB/s | 6.6 MB     00:03
    node01: --------------------------------------------------------------------------------
    node01: Total                                           935 kB/s | 9.7 MB     00:10
    node01: Running transaction check
    node01: Transaction check succeeded.
    node01: Running transaction test
    node01: Transaction test succeeded.
    node01: Running transaction
    node01:   Preparing        :                                                        1/1
    node01:   Installing       : vim-filesystem-2:8.2.2637-16.el9_0.3.noarch            1/6
    node01:   Installing       : vim-common-2:8.2.2637-16.el9_0.3.x86_64                2/6
    node01:   Installing       : tcl-1:8.6.10-7.el9.x86_64                              3/6
    node01:   Installing       : gpm-libs-1.20.7-29.el9.x86_64                          4/6
    node01:   Installing       : vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64              5/6
    node01:   Installing       : expect-5.45.4-15.el9.x86_64                            6/6
    node01:   Running scriptlet: expect-5.45.4-15.el9.x86_64                            6/6
    node01:   Verifying        : expect-5.45.4-15.el9.x86_64                            1/6
    node01:   Verifying        : gpm-libs-1.20.7-29.el9.x86_64                          2/6
    node01:   Verifying        : vim-common-2:8.2.2637-16.el9_0.3.x86_64                3/6
    node01:   Verifying        : vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64              4/6
    node01:   Verifying        : tcl-1:8.6.10-7.el9.x86_64                              5/6
    node01:   Verifying        : vim-filesystem-2:8.2.2637-16.el9_0.3.noarch            6/6
    node01:
    node01: Installed:
    node01:   expect-5.45.4-15.el9.x86_64
    node01:   gpm-libs-1.20.7-29.el9.x86_64
    node01:   tcl-1:8.6.10-7.el9.x86_64
    node01:   vim-common-2:8.2.2637-16.el9_0.3.x86_64
    node01:   vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64
    node01:   vim-filesystem-2:8.2.2637-16.el9_0.3.noarch
    node01:
    node01: Complete!
    node01: StrictHostKeyChecking no
    node01: Generating public/private rsa key pair.
    node01: Your identification has been saved in /home/vagrant/.ssh/id_rsa
    node01: Your public key has been saved in /home/vagrant/.ssh/id_rsa.pub
    node01: The key fingerprint is:
    node01: SHA256:PPjIrHiv8L7stBdHOSXdsr6d5XQzOGwZNBnGcl73+Tw root@node01
    node01: 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 node01
    node01: 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: nat
    node02: 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:2200
    node02: SSH username: vagrant
    node02: SSH auth method: private key
    node02:
    node02: Vagrant insecure key detected. Vagrant will automatically replace
    node02: 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 of
    node02: VirtualBox! In most cases this is fine, but in rare cases it can
    node02: prevent things such as shared folders from working properly. If you see
    node02: shared folder errors, please make sure the guest additions within the
    node02: virtual machine match the version of VirtualBox you have installed on
    node02: your host and reload your VM.
    node02:
    node02: Guest Additions Version: 6.1.34
    node02: VirtualBox Version: 7.0
==>node02: Setting hostname...
==>node02: Configuring and enabling network interfaces...
==>node02: Mounting shared folders...
    node02: /vagrant =>C:/vagrant
    node02: /home/vagrant/share =>C:/vagrant/share
==>node02: Running provisioner: shell...
    node02: Running: C:/Users/lugng/AppData/Local/Temp/vagrant-shell20221204-9852-y6myp9.sh
    node02: AlmaLinux 9 - AppStream                         1.4 MB/s | 7.0 MB     00:04
    node02: AlmaLinux 9 - BaseOS                            688 kB/s | 2.0 MB     00:02
    node02: AlmaLinux 9 - Extras                            8.3 kB/s |  17 kB     00:01
    node02: 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     Size
    node02: ================================================================================
    node02: Installing:
    node02:  expect             x86_64     5.45.4-15.el9                appstream     246 k
    node02:  vim-enhanced       x86_64     2:8.2.2637-16.el9_0.3        appstream     1.8 M
    node02: Installing dependencies:
    node02:  gpm-libs           x86_64     1.20.7-29.el9                appstream      20 k
    node02:  tcl                x86_64     1:8.6.10-7.el9               baseos        1.1 M
    node02:  vim-common         x86_64     2:8.2.2637-16.el9_0.3        appstream     6.6 M
    node02:  vim-filesystem     noarch     2:8.2.2637-16.el9_0.3        baseos         20 k
    node02:
    node02: Transaction Summary
    node02: ================================================================================
    node02: Install  6 Packages
    node02:
    node02: Total download size: 9.7 M
    node02: Installed size: 39 M
    node02: Downloading Packages:
    node02: (1/6): gpm-libs-1.20.7-29.el9.x86_64.rpm         52 kB/s |  20 kB     00:00
    node02: (2/6): expect-5.45.4-15.el9.x86_64.rpm          372 kB/s | 246 kB     00:00
    node02: (3/6): tcl-8.6.10-7.el9.x86_64.rpm              991 kB/s | 1.1 MB     00:01
    node02: (4/6): vim-filesystem-8.2.2637-16.el9_0.3.noarc 128 kB/s |  20 kB     00:00
    node02: (5/6): vim-enhanced-8.2.2637-16.el9_0.3.x86_64. 993 kB/s | 1.8 MB     00:01
    node02: (6/6): vim-common-8.2.2637-16.el9_0.3.x86_64.rp 1.4 MB/s | 6.6 MB     00:04
    node02: --------------------------------------------------------------------------------
    node02: Total                                           1.2 MB/s | 9.7 MB     00:07
    node02: Running transaction check
    node02: Transaction check succeeded.
    node02: Running transaction test
    node02: Transaction test succeeded.
    node02: Running transaction
    node02:   Preparing        :                                                        1/1
    node02:   Installing       : vim-filesystem-2:8.2.2637-16.el9_0.3.noarch            1/6
    node02:   Installing       : vim-common-2:8.2.2637-16.el9_0.3.x86_64                2/6
    node02:   Installing       : tcl-1:8.6.10-7.el9.x86_64                              3/6
    node02:   Installing       : gpm-libs-1.20.7-29.el9.x86_64                          4/6
    node02:   Installing       : vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64              5/6
    node02:   Installing       : expect-5.45.4-15.el9.x86_64                            6/6
    node02:   Running scriptlet: expect-5.45.4-15.el9.x86_64                            6/6
    node02:   Verifying        : expect-5.45.4-15.el9.x86_64                            1/6
    node02:   Verifying        : gpm-libs-1.20.7-29.el9.x86_64                          2/6
    node02:   Verifying        : vim-common-2:8.2.2637-16.el9_0.3.x86_64                3/6
    node02:   Verifying        : vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64              4/6
    node02:   Verifying        : tcl-1:8.6.10-7.el9.x86_64                              5/6
    node02:   Verifying        : vim-filesystem-2:8.2.2637-16.el9_0.3.noarch            6/6
    node02:
    node02: Installed:
    node02:   expect-5.45.4-15.el9.x86_64
    node02:   gpm-libs-1.20.7-29.el9.x86_64
    node02:   tcl-1:8.6.10-7.el9.x86_64
    node02:   vim-common-2:8.2.2637-16.el9_0.3.x86_64
    node02:   vim-enhanced-2:8.2.2637-16.el9_0.3.x86_64
    node02:   vim-filesystem-2:8.2.2637-16.el9_0.3.noarch
    node02:
    node02: Complete!
    node02: StrictHostKeyChecking no
    node02: Generating public/private rsa key pair.
    node02: Your identification has been saved in /home/vagrant/.ssh/id_rsa
    node02: Your public key has been saved in /home/vagrant/.ssh/id_rsa.pub
    node02: The key fingerprint is:
    node02: SHA256:s9H1SMf4cKCguICPZt/p1b3lVow4/RvVZ62qgNkf+u4 root@node02
    node02: 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 node01
    node02: 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<

创建虚拟机彼此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<

修改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 = 2
  end
  
  (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"
	  end
	end

	config.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.sh
    node02: ======>node01 ssh in...
    node02: spawn ssh vagrant@node01 /home/vagrant/sshcpid.sh
    node02: Warning: Permanently added 'node01' (ED25519) to the list of known hosts.
vagrant@node01's password:
    node02: ======>node01 ssh-copy-id... \n
    node02: spawn ssh-copy-id vagrant@node01
    node02: /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 installed
    node02: /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: vagrant
    node02:
    node02:
    node02: Number of key(s) added: 1
    node02:
    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... \n
    node02: spawn ssh-copy-id vagrant@node02
    node02: /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 installed
    node02: /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: vagrant
    node02:
    node02:
    node02: Number of key(s) added: 1
    node02:
    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.sh
    node02: Warning: Permanently added 'node02' (ED25519) to the list of known hosts.
vagrant@node02's password:
    node02: ======>node01 ssh-copy-id... \n
    node02: spawn ssh-copy-id vagrant@node01
    node02: /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 installed
    node02: /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: vagrant
    node02:
    node02:
    node02: Number of key(s) added: 1
    node02:
    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... \n
    node02: spawn ssh-copy-id vagrant@node02
    node02: /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 installed
    node02: /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: vagrant
    node02:
    node02:
    node02: Number of key(s) added: 1
    node02:
    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两台机器的公匙,表明这两台机器能够免密登录了。

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


网页题目:Windows下虚拟机的自动化管理-创新互联
文章URL:http://kswsj.cn/article/cddhds.html