Virtualbox as service windows

The method with srvstart works pretty well, however it does not stop the service at shutdown properly, such that it stops with poweroff.

What however works nicely is the «net stop <service>» command.

I used it in the general shutdown script of my computer and looks like it works (savestate returns).

—————————-

Shutdown scripts can be accessed via gpedit.msc under computer configuration/windows settings/scripts.

I created a .bat file with a net stop command.

Furthermore is it possible to activate the output of that shutdown see script. gpedit.msc Administrative templates/system/scripts/

When you install the service with the windows service commander you can also modify the rights of common users (for example to start or stop the service) (security options)

——————————

Furthermore I intend to have a user that can use the VBoxmanage commands.
For that this user will have to have a console which runs under local service rights.

This can be done with the psexec tool from sysinternals (windows resource kit tools) with the -i -s options (but only from a shell with admin rights):

1. runas /user:<admin> cmd
2. psexec -i -s cmd (inside the new shell)

within this shell Virtualbox sees the machines running under localsystem.

———————————
Interesting could be also a service that runs a shell and can be started and stopped only by the user that manages the Virtualbox machines.

Anyway all this is slightly dangerous because of the localsystem rights (which are practically admin rights)

But probably the service could be also run under the useracount or the localservice account
The problem is only that Virtualbox sees its running virtual machine

———————————
For hiding the console window I used startx (which also allows you to set the priority better)

———————————

I realised that even Virtualbox.exe can be run under localsystem and it sees the running virtual machine!
It does neither shutdown the VBoxheadless.exe when it is closed. Interesting…

best
Sönke Schmachtel

VBoxVmService

1. What is VBoxVmService?

VBoxVmService is a Windows Service, that enables the host-system to run or shutdown VirtualBox Virtual Machines (VMs) without a user being logged on to the host-system running Windows (Win10/2012/2016, both x86 and x64 supported).

2. How to use VBoxVmService?

Check the detailed howto guide.

If you run into problem, please follow the TROUBLESHOOTING section in the guide first, most likely your issue has been addressed there. Check for known issues on the wiki before submitting new issue.

3. How does it work?

Basically, VBoxVmService is just a wrapper-service that calls VirtualBox COM API interfaces.

When windows starts up, the wrapper-service will start running. It will check for the settings in VBoxVmService.ini file, and call up the Virtual Machines as specified. Both the wrapper-service and Virtual Machines are run with the account specified in the VBoxVmService.ini file.

If RunWebService=yes is specified in VBoxVmService.ini file, the wrapper-service will also try to start VirtualBox web service automatically. This might be useful for people who use the web service a lot, like users of phpVirtualBox.

When windows shuts down, the wrapper-service will try to stop all the VMs configured in VBoxVmService.ini.

VmServiceControl.exe is the CLI (command line interface) client that sends control commands to VBoxVmService and display returned results.

VmServiceTray.exe is another client like VmServiceControl.exe, but comes with GUI interface and stays in system tray.

If you are interested in further details, feel free to browse the supplied source codes!

4. What are the plans for the future?

Actually, there are no plans for future releases of this software, other than keeping it updated so that it can always work with latest version of VirtualBox.

5. Which versions of Windows are supported?

Old Windows versions like Windows 7 are no longer supported.

It hasn’t been fully tested on systems other than Windows 10, but it is supposed to work on server systems like Win2012, Win2016, … etc, both 32bit and 64bit versions.

6. Will VBoxVmService run on Mac OS-X or Linux?

No. VBoxVmService is specially designed to suit the Windows operating system. And it doesn’t need to run on Mac OS-X or Linux because these platforms supply adequate features to accomplish the same effect.

7. Credits

First version of VBoxVmService, patching together the C++ code of VBoxVmService and the helper tool «sleep.exe», messing with some c# for «bcompile.exe» plus all the batch-scripting was done by Mathias Herrmann.

Only Fang joined the project in August 2010, and had become main contributor since then. He re-designed the service, added VmServiceControl.exe to do all the controlling job and changed VBoxVmService.exe to become a pure service program.

Runar Buvik joined the project in December 2010, bringing lots of creative improvements like two way communication between the service and control program, new commands to show current VM status and check service environment, etc.

  • Home
  • Products
  • AlwaysUp
  • Applications
  • VirtualBox

How to Run a VirtualBox Virtual Machine as a Windows Service with AlwaysUp

Ensure that your VirtualBox VM starts immediately when your PC boots and is available 24/7. No login necessary!

VirtualBox is a free, open-source virtualization platform that can host Windows, Linux, Mac OS and other operating systems.

To run your VirtualBox VM with AlwaysUp:

  1. Download and install VirtualBox if necessary.

    Create a virtual machine (VM) and ensure that everything works as you expect.

    Be sure to
    install the VirtualBox extension pack
    if you intend to use VirtualBox’s
    Remote Display feature to connect to your VM.

  2. Download and install AlwaysUp, if necessary.

  3. Start AlwaysUp.

  4. Select Application > Add to open the Add Application window:

    Add Application

  5. On the General tab:

    • In the Application field, enter the full path to the
      VBoxHeadless.exe application,
      which allows you to start a VM without a graphical interface.

      If you installed VirtualBox in the default location, this is:

      C:\Program Files\Oracle\VirtualBox\VBoxHeadless.exe

    • In the Arguments field, enter:

      -startvm «<VIRTUAL-MACHINE_NAME>»

      where <VIRTUAL-MACHINE_NAME> is the name of the VirtualBox VM you would like to start automatically.
      We have specified «Windows Server 2022» in this tutorial.

      Note: Instead of starting your VM by name, can launch it using the VM’s unique identifier (UUID).
      To do so, specify parameter -s <UUID> (instead of -startvm),
      where <UUID> is the identifier for your VM.
      You can list your VM’s UUIDs by running
      Vboxmanage.exe list vms
      from the VirtualBox installation folder.

    • In the Start the application field, select Automatically, but shortly after the computer boots.

      This setting — which delays VM startup by about 2 minutes — should ensure that critical system services
      (like networking and domain authentication) are ready and waiting when your virtual machine is launched in the background.

    • In the Name field, enter the name that you will call this application in AlwaysUp.
      We have specified «Windows Server 2022 VM» but you can enter virtually anything you like.

    VirtualBox Windows Service: General Tab

  6. Click over to the Logon tab.
    Enter the user name and password of the account in which you installed and run VirtualBox.
    AlwaysUp must run your VM must in this account so that it can find its settings:

    VirtualBox Windows Service: Logon Tab

  7. Move to the Startup tab and check the Ensure that the Windows Networking components have started box.
    This informs AlwaysUp that VirtualBox needs the TCP/IP networking stack to operate.

    VirtualBox Windows Service: Startup Tab

  8. And finally, on the Extras tab, let’s ensure that your VM shuts down smoothly when its stopped.

    • Check the Use this special command to stop the application box.
      Enter the full path to the VBoxManage.exe application along with a few arguments:

      «C:\Program Files\Oracle\VirtualBox\VBoxManage.exe» controlvm <VIRTUAL-MACHINE-NAME> savestate

      where <VIRTUAL-MACHINE-NAME> is the name of your VM.

      See the VBoxManage.exe command line arguments for stopping a VM if you wish to stop without saving state, etc.

      Note: VirtualBox user Jesse Connor prefers to use ACPI shutdown instead of savestate because his Linux boxes
      don’t seem to recover smoothly from saved states.
      For the stop command, he specifies:

      «C:\Program Files\Oracle\VirtualBox\Vboxmanage.exe» controlvm <UUID> acpipowerbutton

      where <UUID> is the identifier for his VM.

    • Check the Wait for up to box and enter 30 in the accompanying field.
      This tells AlwaysUp to wait for up to 30 seconds for VirtualBox to exit properly before forcibly closing it.

    VirtualBox Windows Service: Extras Tab

  9. Click the Save button. In a couple of seconds, your new application will show up in the AlwaysUp window.
    It’s not yet running though:

    VirtualBox Windows Service: Created

  10. To start your VirtualBox VM, choose Application > Start «Windows Server 2022 VM» (your application name will be different though).

    In a few seconds, the entry’s state will transition to «Running» and your VM will be chugging away in the background
    (in the isolated Session 0):

    VirtualBox Windows Service: Running

    At this point, please connect to your VM and ensure that it works as expected.

    For example, if you set up the Remote Display feature,
    now would be a good time to open an RDP session to your VM.

  11. That’s it! Next time your computer boots, your VirtualBox virtual machine will start up immediately, before anyone logs on.

    We encourage you to edit your VirtualBox entry in AlwaysUp and explore the many other settings that may be appropriate for your environment.
    For example, send an email if VirtualBox stops unexpectedly, boost the priority of the VM process, and much more!


VirtualBox not working properly as a Windows Service?

  • Please ensure that the VirtualBox commands work as expected on your system.

    For example, does this command start your virtual machine?

    C:\Program Files\Oracle\VirtualBox\VBoxHeadless.exe -startvm «<VIRTUAL-MACHINE_NAME>»

    VirtualBox Windows Service: Created

    And does this command stop your VM?

    «C:\Program Files\Oracle\VirtualBox\VBoxManage.exe» controlvm <VIRTUAL-MACHINE-NAME> savestate

    If not, you should adjust your AlwaysUp settings to use alternate commands that work for you.
    Please get in touch if you need help doing that.

  • Visit the AlwaysUp Troubleshooter — our online tool
    that can help you resolve the most common problems encountered when running VirtualBox as a windows service.

  • From AlwaysUp, select Application > Report Activity > Today… to bring up a HTML report detailing the
    interaction between AlwaysUp and VirtualBox.
    The AlwaysUp Event Log Messages page explains the more obscure messages.

  • Consult the AlwaysUp FAQ for answers to commonly
    asked questions and troubleshooting tips.

  • Contact us and we will be happy to help!

In this article, we will guide you through the process of installing VirtualBox as a Windows service using NSSM (Non-Sucking Service Manager) and starting a Virtual Machine automatically as a service. This can be useful for scenarios where you need a Virtual Machine to run in the background, even when the user is not logged in.

Prerequisites

Before we begin, ensure that you have the following prerequisites in place:

  1. VirtualBox: You should have VirtualBox installed on your Windows machine. You can download it from the official VirtualBox website.

  2. NSSM (Non-Sucking Service Manager): NSSM is a tool that allows you to create and manage Windows services. We recommend installing it via Chocolatey (Choco), a popular package manager for Windows. If you haven’t installed Choco, you can download and install it from the Chocolatey website.

    To install NSSM using Chocolatey, open a Command Prompt with administrator privileges and run the following command:

Now, let’s proceed with installing VirtualBox as a Windows service:

  1. Open Command Prompt as Administrator: Right-click on the Command Prompt icon and select “Run as administrator” to ensure you have the necessary privileges.

  2. Install VirtualBox as a Service: Run the following NSSM command to install VirtualBox as a service. Replace <VIRTUAL-MACHINE_NAME> with the name of your Virtual Machine:

    1
    
    nssm install VirtualBoxVM
  3. Configure Service Parameters:

    • Application Path: Set the path to the VBoxHeadless.exe executable. By default, it’s located in “C:\Program Files\Oracle\VirtualBox\VBoxHeadless.exe.”

      1
      
      Path: C:\Program Files\Oracle\VirtualBox\VBoxHeadless.exe
    • Arguments: Specify the -startvm parameter followed by the name of your Virtual Machine.

      1
      
      Arguments: -startvm <VIRTUAL-MACHINE_NAME>
  4. Save Configuration: Click on the “Install service” button to save the configuration. You should see a message indicating that the service has been installed.

  5. Start the Service: You can start the service immediately using the following command:

    This command will start your Virtual Machine as a service.

Managing the VirtualBox Service

You’ve successfully installed VirtualBox as a Windows service using NSSM. To manage the service, you can use standard Windows service management tools or commands, such as:

  • To start the service:

  • To stop the service:

  • To check the status of the service:

Now, your Virtual Machine will run as a service, allowing you to use it without the need for manual intervention, even when you are not logged into the system.

VirtualBox — замечательный во многих отношениях бесплатный гипервизор, обладающий, между прочим, рядом скрытых возможностей вроде быстрого увеличения размера динамического виртуального диска в командной строке с помощью встроенного модуля VBoxManage. Но по сравнению с платными продуктами его функционал всё же ограничен, например, он не умеет работать как служба Windows, в фоновом режиме.

Чтобы реализовать такую возможность, понадобится сторонняя утилита VBoxVmService. Для чего? Чтобы иметь возможность запускать виртуальные машины без входа пользователя в учетную запись на хостовом компьютере.

Несмотря на свое «серверное» предназначение, утилита VBoxVmService достаточно проста в использовании.

Установив тулзу, перейдите в расположение установки C:\vms и откройте расположенный там файл VBoxVmService.ini любым текстовым редактором.

Папка vms

В этом файле имеются три блока настроек: [Settings], [Vm0] и [Vm1].

  • Settings — Основная настройка. Здесь в качестве параметра VBOX_USER_HOME вам нужно указать путь к каталогу с вашими виртуальными машинами.
  • Vm0 — Настройки конкретной виртуальной машины. В качестве параметра VmName задаем имя этой VM, параметр ShutdownMethod определяет метод завершения ее работы. По умолчанию используется savestate, означающий автоматическое сохранение виртуальной машины, если же вы выставите acpipowerbutton, то VM будет выключена полностью. Параметр AutoStart отвечает за автозапуск виртуальной машины при загрузке хостового компьютера. Может принимать два значения yes и no. По умолчанию, естественно, выставлено «yes», ведь вы не входите в свою учетную запись Windows.
  • Vm1 — Всё то же самое, что и Vm0, только эта гипотетически существующая WM отключена. Если вам нужно запустить две виртуальные машины, тогда редактируем этот блок соответствующим образом и меняем AutoStart с no на yes.

VBoxVmService.ini

Теперь, чтобы запустить утилиту, а вместе с ней и виртуальные машины, в меню значка VBoxVmService в трее выбираем «Start VBoxVmService».

Меню значка VBoxVmService

Или запускаем сервис через командную строку командой VBoxVmService.exe -i, предварительно перейдя в папку с исполняемым файлом.

VBoxVmService

Перезагружаем компьютер.

Указанные виртуальные машины должны запуститься.

Скачать последнюю версию утилиты можно на странице разработчика github.com/onlyfang/VBoxVmService/releases.

Программа совместима с Windows 10 и Windows Server 2012/2016, обычной десктопной «восьмерке» приложение работать не будет.

На данный момент утилита совместима с VirtualBox 6.1, поддержка в будущем новых версий разработчиком не гарантируется.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как обрезать видео на ноутбуке windows 10
  • Размер windows 11 после установки
  • Как обновить биос гигабайт на компьютере windows 10
  • Как запустить геймпад на пк windows 10
  • Error unknown filesystem entering rescue mode grub rescue windows 10