Windows Server и KVM на Linux
Сегодня постараюсь описать все трудности в пути установки операционной системы (ОС) семейства Windows (а конкретнее Windows Server 2008 R2) на виртуальную машину KVM (используется qemu-kvm) в ОС Linux (а именно Debian 7)
Сложностей с установкой kvm возникнуть не должно
Далее необходимо скопировать установочный образ операционной системы куда-нибудь на диск. К примеру можно скопировать в
sudo dd if=/dev/cdrom of=Window_Server_2008_R2.iso
Самое необходимое: скачайте драйвера virtio, без них установка будет очень-очень долгой.
Затем создадим папку для файлов виртуального жёсткого диска
И сам файл виртуального жёсткого диска, где 25G — его размер
qemu-img create -f qcow2 WIN2K8R2.qcow2 25G
и самое главное — запуск самой виртуальной машины.
qemu-system-x86_64 —enable-kvm -m 2048 -boot d -drive file=WIN2K8R2.qcow2,if=virtio -cdrom Win2K8X64R2Ent.iso -drive file=virtio-win-drivers-20120712-1.iso,media=cdrom -net nic,model=virtio -net user
, где -m 2048 — объём оперативной памяти для неё, WIN2K8R2.qcow2 — файл виртуального жёсткого диска, созданного ранее, if=virtio — источник драйверов для подключения жёсткого диска к виртуальной машине, Win2K8X64R2Ent.iso — образ операционной системы.
К сожалению, мне пришлось подключаться к удалённому рабочему столу, потому что по ssh установить Windows не удавалось, система требовала графический интерфейс.
Для запуска qemu под юзером производим следующие шаги:
Редактируем /etc/libvirt/qemu.conf, чтобы виртуальные машины работали у нас от непривилегированного пользователя:
user = «username»
group = «libvirt»
Поскольку у нас будут использоваться tun-устройства, нужно выставить capability CAP_NET_ADMIN, сделать это можно как для отдельного исполняемого файла, так и для пользователя в целом, или настроить чтобы libvirt не сбрасывал нужные права для qemu/kvm.
Выставляем для отдельного файла:
sudo setcap cap_net_admin=ei /usr/bin/kvm
Или выставляем для пользователя в целом в файле /etc/security/capability.conf:
Или выставляем соответствующую настройку в /etc/libvirt/qemu.conf:
Добавим пользователя в группу libvirt и kvm:
# adduser username libvirt
Установка Windows Server проста до безобразия, если знать когда подсунуть файлы драйверов для жёсткого диска.
Приведу краткий перечень действий, необходимых для корректной установки:
- Нажимаем Install
- Выбираем тип ОС
- Соглашаемся с лицензионным соглашением
- Выбираем Полная установка
- Щёлкаем по ‘Загрузить драйвер’
- Обзор
- Выбираем диск с драйверами Virtio. дисков должно быть два: один с Windows, другой — с драйверами.
- Выбираем ‘Virtio Drivers’ => STORAGE => SERVER2008R2 => AMD64
- OK
- Драйвер ‘Red Hat VirtIO SCSI controller’ будет выбран. Если его не видно, значит что то пошло не так 🙁
- Жмакаем Далее. Драйвер загрузится и вернёт на экран выбора дисков для установки ОС. Если размер не меняли, то там будет 25 Гб.
- Щёлкаем на пустом диске и жмём Далее. Всё. Установка идёт стандартным путём.
Единственная трудность случилась в конце установки, когда нужно придумать пароль для учётной записи администратора. Через RDP почему то не печатались иностранные символы, пришлось воспользоваться экранной клавиатурой.
Потребление памяти и утилизация процессора в пределах нормы и не превышала пары процентов при простое системы. Проц — Celeron G1620 🙂
Теперь осталось пробросить эту машину во внешку и подключится к ней по RDP, минуя RDP хостовой системы. Это пока не решено.
Windows Server 2019/Windows 10 VM on QEMU/KVM on Ubuntu 18.04
This page documents how to set up Windows Server 2019 under QEMU/KVM on Ubuntu 18.04. I suspect the procedure is identical for Windows 10 and somewhat newer Ubuntu versions.
What you will need:
- An Ubuntu 18.04 server
- QEMU/KVM installed on it. This is good documentation: https://help.ubuntu.com/community/KVM/Installation
- A Windows Server 2019 or Windows 10 ISO. You can download them from Microsoft for free and try them for 180 days. Good enough for a test lab.
- The virtio driver iso, which you can download here [deeplink].
ISO locations
It is customary to put boot ISOs in /var/lib/libvirt/boot/ and the disk images in /var/lib/libvirt/images. Other places are fine but if you choose to put your disk images in a different location keep in mind you should tell Apparmor about it lest you get bothered with permissions issues.
This document will not describe backing up and restoring of VMs, nor will it explain snapshotting. Both are interesting in their own right and you should learn about them if you haven’t. I wanted to document specifically the process of installing and configuring a Windows Server 2019/Windows 10 guest.
Overview
1. Setting up the network interface
2. Installing the virtual machine
3. Installing drivers and the guest agent
4. Non-related tips
Setting up the network interface
I’m setting up a bridge interface for the VMs to use. By doing this the VMs will show up in my LAN on a regular LAN IP address. My subnet is 192.168.178.0/24. My host’s IP address is 192.168.178.18.
Open the file /etc/netplan/01-netcfg.yaml, or whatever .yaml file is in /etc/netplan.
Mine looked like this:
Edit the file to look like this:
Be careful when editing this file; it’s easy to lock yourself out. Things to be aware of:
- netplan is very picky about indentations. You need to get this right.
- Instead of # netplan apply do netplan try :
If all goes well do
You will end up with a physical interface that provides both the host and the VMs access to your LAN.
In case you have a separate network interface for your VMs try this configuration (enp7s0 and enp4s0f1 are both interfaces on my server; I want the VMs to use interface enp4s0f1 and use enp7s0 for management of the host machine itself):
Installing the VM
When I tried this on Ubuntu 20.04 with a Windows 10 VM I got a bunch of warning and errors and needed to do this:
The difference is the –cdrom specification instead of the –disk one. Also it now seems to require a –boot parameter. The rest of this article continues from the previous command, not the one in this note.
Let me break that down.
First of all, run the command as root or do sudo. The command for installing new VMs is virt-install. Do read its man page.
The VM’s name. In KVM terms this is called it’s domain. please note this name is case sensitive.
The amount of ram in kilobytes
Tells KVM to use the host’s cpu specifications for caching. If you’re planning on using clustering or live migration read up on this part in virt-install’s man page.
Do full instead of para virtualisation, if available
Give the VM two virtual CPU cores. Again, read the man file for interesting values, like auto.
The VM will be optimized for this OS type.
for a full list of supported OS variants. Pick the closest one.
Create a disk at this location with this name. I tend to use the .img extension but .qcow2 is also common. The size is in gigabytes. Because we’re using Qemu we’ll be using the virtio bus driver. Note that we will need to install this driver in order to install Windows on the disk.
We’re connecting the Windows ISO file to a CD ROM device here.
This is the driver CD ROM ISO file. This contains the driver for the drive we’ll be installing Windows on.
Which network interface to install on the VM.
Tell the VM what to do with graphics output. In this case we’ll send it through a VNC interface listening on any address (0.0.0.0) on port 5904. Check the man page for more options. 5900 is VNC’s default port but I’m already running something on that port so I’m specifying a different number.
Do not verify if the CD ROM is already in use by another VM.
Let’s kick off the installation and connect using your favourite VNC client. I used this one.
Connect VNC to your HOST’s IP address followed by the port you specified. The warning is because we didn’t specify a VNC password. That’s ok for now.
The Windows installer will inform you that there are no drives to install on and would like to add a driver?
Choose the virtio scsi driver. In my case the CD ROM ISO was mounted on e:.
Proceed as normal. At one point the installer will reboot and the connection will get lost. Reconnect and continue the installation.
Installing drivers and the guest agent
The guest agent facilitates communication between host and guest. Among other things this will make the VM shutdown gracefully when rebooting or shutting down the host.
After installation shut down the VM and do
This will allow you to directly edit the VM’s definition in the form of an XML file. Look up the section and within it add this section:
The W2K19.agent part (second line) must be unique per server. Again, the path can be anything but if you deviate from this standard you must tell Apparmor about it. I suggest you stick to the path above.
Start the server:
In the VM start the Device Manager. Note there are two devices that lack drivers. Rightclick them, choose Update driver and have the wizard search e: and subfolders.
One is the virtio Balloon Drivers, which allows for memory thin provisioning. The other is the virto serial driver, which is used by the virtio guest agent to facilitate communication between host and guest.
Shut down the VM and restart it with
To test agent communication, do
This should result in quite a bit of information.
If communication cannot be established your will see “error: argument unsupported: QEMU guest agent is not configured”.
Non-related tips
- Use tmux, a terminal multiplexer like screen. It allows you to do more than one thing at a time on your terminal and is highly customizable.
- Use BgInfo to easily see which VM you are managing.
- Learn about KVM snapshots and backups.
4 Comments
“Look up the section and within it add this section:”
Looks like you forgot to specify ” section. Otherwise, very useful article.
Ah, I see. The blog engine has discarded the angular quotes. «devices»
So, to sum up my two previous comments, this part:
“Look up the section and within it add this section:”
should be:
“Look up the section and within it add this section:”
Установка Windows на KVM
Установка Windows на KVM для опытных системных администраторов не составит труда. Тем не менее, в процессе развертывания ОС и создания под неё виртуальной машины могут встретиться ряд нетривиальных проблем , связанных с особенностями KVM. О них я и расскажу.
Если вам интересна тематика Debian и связанных с ним приложений, рекомендую обратиться к тегу Debian на моем блоге
Установка Windows на KVM
К настоящему моменту у меня уже есть сервер с KVM. На нем также сконфигурирована сеть и хранилище гостевых дисков. Все это я подробно расписал в своей предыдущей статье Установка гипервизора KVM.
Для создания виртуальной машины я буду использовать утилиту virt-install.
Конфигурация виртуальной машины
Есть ряд базовых параметров, без указания которых создание виртуальной машины с помощью virt-install невозможно — это имя ВМ, объем оперативной памяти, настройки диска и параметры установки. Тем не менее, для наглядности я укажу и другие опции, которые так или иначе используются не реже обязательных.
Команда для создания виртуальной машины:
- —-os-type windows — Устанавливает более подходящие аппаратные настройки для конкретной ветки ОС;
- —disk pool=guest_images — Создает виртуальные диски в данном хранилище;
- —graphics vnc,listen=0.0.0.0 — Устанавливаем тип графики. Адрес прослушки необходим, чтобы к vnc могли подключаться удаленные админы. По дефолту разрешены только локальные подключения.
Назначение остальных параметров очевидно.
Если в процессе создания виртуальной машины вы получили ошибку:
Install windows server on kvm
[GUIDE] Install Windows Server through IPMI/KVM (step by step)
How to Install Windows Server 2019 using IPMI or KVM
What is IPMI/KVM?
The Intelligent Platform Management Interface (IPMI) is a set of computer interface specifications for an autonomous computer subsystem that provides management and monitoring capabilities independently of the host system’s CPU, firmware (BIOS or UEFI) and operating system. IPMI defines a set of interfaces used by system administrators for out-of-band management of computer systems and monitoring of their operation. For example, IPMI provides a way to manage a computer that may be powered off or otherwise unresponsive by using a network connection to the hardware rather than to an operating system or login shell. Another use case may be installing a custom operating system remotely. Without IPMI, installing a custom operating system may require an administrator to be physically present near the computer, insert a DVD or a USB flash drive containing the OS installer and complete the installation process using a monitor and a keyboard. Using IPMI, an administrator can mount an ISO image, simulate an installer DVD, and perform the installation remotely.
A dedicated server with IPMI Access enabled
Google Chrome Browser
Java must be Installed on your machine
Good Internet speed
Guide to Install Windows Server 2019 using IPMI/KVM
You machine should have Java installed. Otherwise Download & install JAVA from here: https://www.java.com/en/download/
Through out this Tutorial, I am going to use https://oneprovider.com dedicated server [https://oneprovider.com/dedicated-servers] & Windows Server 2019 Essentials edition (free evaluation copy)
Oneprovider is a world leading company for web servers. And one of the cheapest DEDI/BOX provider in the industry(with 0 setup fee).
Also their support system is very helpful.
Their payment method includes Paypal with many other familiar payment methods.
In maximum cases, their servers comes with IPMI or iDRAC access
After receiving server information from Oneprovider, incase No Operating System is installed on your server, go to «Server manage» page and click on ‘Install’ tab. Otherise click on «IPMI Session» Tab
From there you can craete an IPMI session for your System IP.
After clicking on «Create Session» button, you should wait for 2 minutes, after that IPMI URL and its credential is visible to you.
Anyway, you are welcome to choose any other Dedicated provider, which could allow you to have an access of IPMI/iDRAC/KVM
Download the OS
you can have your own iso copies from Microsoft Official site here: https://www.microsoft.com/en-us/evalcenter/evaluate-windows-server
Download from my Archive below:
Widows Server 2019 (evaluation copy/180 days free trial)
Widows Server 2016 (evaluation copy/180 days free trial)
Widows Server 2012 R2 (evaluation copy/180 days free trial)
Widows Server 2008 R2 (evaluation copy/180 days free trial)
Download extra dependent server software