Автоматический запуск virtualbox linux

Автозапуск виртуальной машины VirtualBox

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

В этой небольшой статье мы рассмотрим как настроить автозапуск виртуальной машины VirtualBox с помощью системы инициализации systemd, которая сейчас используется повсеместно.

Автозапуск виртуальной машины в VirtualBox

Давайте создадим файл юнита, который будет управлять автозагрузкой. Для этого выполните такую команду:

В открывшемся редакторе вставьте такой текст:

С помощью этого юнита мы и будем делать автозапуск virtualbox linux. В этом примере я запускаю виртуальную машину от имени пользователя root, но вам нужно запускать её от того пользователя, к которому добавлены виртуальные машины и от имени которого VirtualBox обычно работает.

Сохраните изменения в файле и выполните следующую команду, чтобы система инициализации перечитала конфигурационные файлы с диска:

В нашем юнит файле мы предусмотрели возможность использования параметра, в котором передается имя или UUID идентификатор виртуальной машины. Если в имени машины есть пробел, то лучше использовать UUID, а иначе можно и имя.

Смотрим список виртуальных машин:

Теперь давайте запустим машину Ubutnu1804 с UUID ed0ce7dd-0ddb-46bf-913c-876671c4d1f1 с помощью systemd:

Если во время запуска произошла ошибка, вы можете посмотреть её выполнив:

В данном случае машина уже была запущена. Я остановил её и запустил ещё раз с уже помощью systemd. Смотрим статус виртуальной машины:

Если всё хорошо, то всё, что нам осталось, это добавить этот сервис в автозагрузку:

Источник

Автоматический запуск virtualbox linux

Autostart Virtualbox VMs

So. certainly things evolve quickly and others lack behind. We’ve got systemd since 15.10 or so and it was the prominent change in 16.04. We actually made the switch for Snap! Websites and that help tremendously as it is very reliable since then (older versions were really bad in comparison.)

At first, I found a Stackoverflow answer describing the old way and it did not work which is why I decided to switch to systemd. I found this page about it and it’s already pretty good! Just a couple of things I had to tweak on my system to make it all work properly.

Deleting the Old Way

Just to make sure it works properly, delete the files from the old environment if you created them. If you did edits to some of them, you probably want to undo those edits.

This is to make sure that the old way doesn’t suddenly kick in and mess up your systemd setup.

On my end, I edited the /etc/default/virtualbox file to add these two variables:

So I went ahead and deleted those two lines.

However, I also changed the following and that I kept:

I prefer to have a good APCI shutdown and a plain power off. If it takes too long to shutdown, we’ll anyway get a power off (a.k.a. a kill).

If you did anything else to try to make the old way work, please make sure to revert that too. You’re on your own on that side of things.

Create Service File

Now you are ready to create a service file.

In mine, I have pretty much the same thing as the one from the page I referenced above, except for the vboxdrv.service . I’m not too sure where that came from, but under Ubuntu 18.04, there is no such thing. Though I remove that one reference.

The script includes two names you need to change:

vm1 — enter the name of your Virtualbox machine (this one appears three times)
alexis — unless you are also an alexis and your account is name like that, change that name

Then save the file under /etc/systemd/system/ .

For example, if you use gvim to edit your files:

Then copy/paste the following and do the edits as expected:

Note: the vboxdrv.service comes from a comment (see below) and should help even further (i.e. I have had problems with my services starting once in a while, most of the time, I still had to restart them by hand—I’ll have to confirm once I reboot that it works every time).

Once the file is ready, you need to tell systemd to reload everything including that new file. It may do so automatically, but just in case here is the command you need:

Читайте также:  Gitlab как пользоваться linux

Now you are ready to use this service.

Note: To see a list of services you have running on your system, the cleanest way is to use the following command:

It automatically sends its output to less so you don’t have to pipe manually. At the bottom of the list comes a brief explaination of what the columns stand for. Especially, if a column says «failed», then the service doesn’t work as expected.

Enable/Start/Stop Service

Now that we created a service file, we want to enable and start it. This supposes that your VM is ready to be started as if you were rebooting your machine.

Note that in the script above, there is nothing to say that one service should be started before and/or after another. It’s doable but you should ask yourself whether it makes sense that the computers should be started in a very specific order. i.e. if something fails on computer B when A isn’t running, it should keep trying until it works.

First, you can test that systemd recognize your file with:

The status command is also useful to check whether a service is running or not.

Now you can start the VM.

It should return on the very next line unless something goes wrong.

If you have the Virtualbox UI open, you should see that it gets started there. The icon changes with what appears on the screen as normal. However, because we use the headless feature, you don’t see the actual GUI part. You can show that window at any time while the machine is running by selecting the » → Show» menu (it’s found in the Machine menu or when you right-click on the VM).

Finally, to make the VM run automatically on a reboot, you need to enable it. This is done using the enable command like so:

You can verify the current status at any time. Note that the enable state shows on its own. There are two entries in the output. Both should be enabled. Here is an example of the output. I highlighted the enabled you are looking for in red:

The last few lines are logs (called journals in systemd) showing what happened. It should say that it started your Virtualbox system.

You can later disable the service like so:

which will prevent it from auto-restarting on a reboot. Note that you can still start a VM marked as being disabled.

Renaming a VM

I use rather long names for my VM that include:

  1. The name of what I’m using the VM for
  2. The OS name (Ubuntu, Fedora, FreeBSD, SunOS, MacOS, etc.)
  3. The hostname of the computer running the VM (because when you run VMs on 3 or 4 different computers, it’s not easy to know what’s what otherwise)
  4. The processor (i86x or amd64)
  5. The sub-name of the computer (i.e. I create clusters that get one VM name + one sub-name such as front end, database, backend. )

I think such long names are great in the Virtualbox interface, but to type in your service file, it may cause problems (between dashes, spaces, parenthesis. and just the fact that such long names are hard to replicate without a few mistakes into them. )

So on my end, I had to rename the VMs. The cool thing, though, is that we now have grouping capabilities. So I can still keep my crazy naming convention for the group, and name each computer in the group something really simple (i.e. _ — for example wordpress_frontend and wordpress_database ).

Where is My VM’s Window?

The script is going to start the VM headless. This is actually important if you were to run the VM on a server without X-Windows. (Yes! It’s doable, I’m just not too sure how you do the installation all by hand. It must be somewhat painful!)

Your VMs are going to start alongside the X-Windows environment and because of that, the X-Windows system may not be ready to open a window in the first place. So instead we start VMs headless.

Читайте также:  Микрофон определяется как наушники windows 10

When you are in the Virtualbox GUI, you see the VMs that are running. They have a green arrow. Right-click on those and select » → Show» to open the window. Now you have full access to the VM’s console. To hide the window again, you can of course minimize. However, if you want to actually close the X-Windows but leave the VM running, use the «Detach GUI» option found under the «Machine» menu.

In older versions (before 5.x), detaching the GUI was done in various ways:

  1. Machine » Detach GUI
  2. View » Close VM
  3. Close VM (as a button)

Various Errors

The virtual machine has terminated unexpectedly during startup with exit code 0 (0x0).

Looking into that one, I could not really see why one of my virtual machine wouldn’t start, especially with an exit code of 0. First I checked that the machine still existed as expected (right location, etc.) It was there.

So next I searched the Internet and found a page which I won’t even link here, it was totally useless except for one small detail: one of the message was one person asking the other what they saw in their log file. Yes. Why wouldn’t I look at that for once.

Here are the last few messages:

And interestingly enough, they give you the exact answer of what to do next (3rd line in the logs above):

  • Sstop all your VMs;
  • Quit VirtualBox;
  • Make sure all the VM services are down (reboot if you want to make 100% sure); and
  • Restart VirtualBox.

Now it should work and it did for me.

The Old Way

At first, I tried the old way, mainly because there are a large number of posts in link with that one. But I just could not find the Virtualbox autostart script anywhere. I tried that once and nothing happened so I would imagine that it’s missing (was removed) in new versions (Ubuntu 18.04 at least).

These are a few points I wanted to make regarding that method.

I go the following error when trying to install a Virtualbox in auto-start mode and trying to fix the problem took me a little while.

The fact is that once you added yourselves to the vboxusers group, you need to log out and back in properly or even just forget about that group for a moment and use your primary group instead.

In other words, the docs I’ve found such as this one:

tell you to use vboxusers but you could also do that:

(Note: in most cases, your primary group name is your username)

and the chmod is not even necessary. Of course, that one won’t help much if you want many users to be able to use the autostart feature. The idea is just to have a way to do your setup before you log out and/or test with a full restart of your computer (in my case, I have a monster with 512Gb of RAM, two processors with a total of 64 threads, it takes forever to reboot so I prefer to avoid it if I can.)

I’ll try again and see whether it works if I restart the computer and I have the correct group in there.

However, I just rebooted and it did not work, there is still something fishy about it under 18.04, I just can’t see the vbox service. I can see the Virtualbox kernel module, just no the service. I probably need to install something else.

Источник

Как автоматически запускать машины Virtualbox при загрузке?

Это смесь. Каждый пакет может быть лицензирован на разных условиях.

Как правило, право изменять его и распространять каждый пакет в основном и юниверсе, некоторые пакеты могут иметь ограничения на это, например, имя и логотип firefox являются товарными знаками, поэтому нельзя использовать без разрешения Mozilla.

Вы можете посмотреть отдельные лицензии на пакеты в / usr / share / doc / * / copyright

13 ответов

Вы можете использовать службу автозапуска VirtualBox. Хороший учебник, описывающий, как это сделать, размещен в блоге «Жизнь администратора-гика» .

Следующие шаги адаптированы из связанного сообщения в блоге:

Сначала вам нужно создать файл /etc/default/virtualbox и добавить несколько переменных.

VBOXAUTOSTART_DB , который содержит абсолютный путь к каталогу базы данных автозапуска, и
VBOXAUTOSTART_CONFIG , который содержит расположение настроек конфигурации автозапуска. Файл должен выглядеть примерно так:

Теперь нам нужно создать файл /etc/vbox/vbox.cfg и добавить

Примечание: Если имя файла vbox.cfg не работает выше, попробуйте назвать его autostart.cfg .

Читайте также:  Как установить windows limbo pc

Если вы единственный пользователь, вы можете просто добавить строку default_policy = allow в файл vbox.cfg .

Установите права доступа к каталогу для группы vboxuser и убедитесь, что пользователи могут писать в каталог, а также придерживаться бита.

Добавьте каждого пользователя в группу vboxusers .

(замените USERNAME именем пользователя)

ПРИМЕЧАНИЕ : Если вы изменили права доступа группы для текущего Пользователь, выйдите и снова войдите, чтобы обновить разрешения. (credit @ kR105)

Каждый пользователь, который хочет включить автозапуск для отдельных машин, должен указать путь к каталогу базы данных автозапуска с помощью

и включить автозапуск для отдельной виртуальной машины с

Это создаст файл myuserid.start в каталоге /etc/vbox

Теперь перезапустите vboxautostart-сервис, чтобы прочитать изменения .

Перезагрузите систему, и ваша виртуальная машина должна запуститься

1 — Создайте файл:

  • Замените «validuser» на ваше имя пользователя
  • Замените «MACHINENAME» с именем вашей виртуальной машины
  • Если вам нужно запустить более 1 машины, повторите строку выше с именем вашей виртуальной машины:

/bin/su validuser -c «/usr/bin/vboxmanage startvm MACHINENAME2—type headless» /bin/sleep 1

2 — Сделать файл vm-start исполняемым:

3 — Редактировать rc.local

Для сервера Ubuntu 16.04.1 LTS я решил это, выполнив:

Сначала активируйте rc-local.service

Добавьте следующую строку в /etc/rc.local

Обратите внимание, что virtual_box_user — это тот, который может видеть, что виртуальная машина (которую вы хотите запустить) выполняет команду:

Измененный /etc/rc.local должен выглядеть следующим образом

Если вы не выберете правильного владельца virtualbox, вы должны увидеть ошибку, набрав команду:

Я надеюсь, что это может помочь

Так я запускаю свой Centos (имя моей виртуальной машины), когда моя хост-машина перезагружается. Я использую crontab для этой работы. Вот моя запись в crontab:

Вы также можете получить описанный здесь менеджер сессий gnome. Gnome Session Manager Он находится в центре программного обеспечения или вы можете просто зайти в терминал и набрать sudo apt-get install gnome-session-common

Далее вы можете создать небольшой скрипт для запуска и использовать менеджер сессий gnome для Начни это. Вот небольшой пример сценария, который поможет вам .

Это можно сделать с помощью интерфейса управления VirtualBox. Просто запустите следующий скрипт при запуске.

Там есть хороший учебник для получения дополнительной информации.

Аддон к @kdmurray ответу.

Если вы получаете сообщение об ошибке:

Чтобы решить эту проблему, мне пришлось вручную создавать файлы «username» .start и «username» .stop с:

И измените владельца с помощью:

, затем перезапустите службу:

проверьте, все ли в порядке с:

и вы должны увидеть процесс «VBox . » в списке, если виртуальная машина запущена

Я нашел более простой способ в Ubuntu 16.04 с VBox 5.1.34.

Находясь в VBox, щелкните правой кнопкой мыши на работающей или неактивной виртуальной машине в списке и выберите «Создать ярлык на рабочем столе». Как только вы увидите значок на рабочем столе, откройте его любым инструментом, который позволит вам увидеть базовый Команда VBox создана (в моей системе я щелкаю правой кнопкой мыши и выбираю «свойства»). Скопируйте это в буфер обмена.

Откройте программу, чтобы обновить «автозагрузку приложений» и создайте новое приложение, которое запускается во время загрузки, вставляя в команде, которую вы скопировали из ссылки на рабочем столе, созданной VirtualBox.

В дополнение к хорошему описанию службы vboxautostart выше, вы можете сделать

для автоматической остановки гостя при завершении работы. Для Ubuntu 14.04 мне пришлось добавить sleep 30 в раздел остановки vboxautostart-service, чтобы он ожидал, пока guest не будет полностью сохранен.

После многих несчастных часов, пытаясь заставить работать процедуры из из kdmurray выше, я безуспешно нашел метод, который работал просто.

Сначала мой Linux-хост (Mint 17) был настроен во время загрузки для автоматического входа в мою основную учетную запись.

Во-вторых, я использовал средства VirtualBox GUI (v4.3.12), чтобы создать ярлык для каждой виртуальной машины на рабочем столе.

Далее: я уже обнаружил, что при вызове Меню-> Центр управления -> Автозагрузка приложений -> Добавить и добавлении ярлыков на рабочем столе были получены файлы, которые не работали, я заметил из другой ответ на этой странице, что расположение стартапов — /home/USERNAME/.config/autostart, поэтому я щелкнул правой кнопкой мыши по каждому из ярлыков виртуальной машины на рабочем столе, а затем вставил их в эту папку, переписав более ранние файлы дерьма. Теперь они разработали «красивые» иконки VirtualBox.

И, конечно же, при перезапуске главного компьютера эти 3 виртуальные машины запускались автоматически.

PS: увы, у меня все еще чего-то не хватает, потому что часто виртуальные машины не запускаются при загрузке, вместо этого они генерируют диалог ошибки окно, в котором написано, что они заблокированы, даже если я сказал им отключиться до перезагрузки хоста.

Источник

Оцените статью