- Как автоматически запускать машины Virtual Box при загрузке?
- 13 ответов
- Как настроить автозапуск виртуальной машины VirtualBox при включении хоста?
- Linux автоматический запуск виртуальной машины
- Autostart Virtualbox VMs
- Deleting the Old Way
- Create Service File
- Enable/Start/Stop Service
- Renaming a VM
- Where is My VM’s Window?
- Various Errors
- The virtual machine has terminated unexpectedly during startup with exit code 0 (0x0).
- The Old Way
Как автоматически запускать машины Virtual Box при загрузке?
У меня в Ubuntu12.04 много виртуальных машин, каждый раз, когда я выключаюсь или перезагружаюсь, я должен запускать их одну за другой.
Я хочу помочь в написании скрипта для автоматического запуска машин VBox при загрузке.
13 ответов
Вы можете использовать сервис автоматического запуска VirtualBox. Хороший учебник, описывающий, как это сделать, размещен в блоге «Life of a Geek Admin».
Следующие шаги адаптированы из связанного сообщения в блоге:
Сначала вам нужно создать файл /etc/default/virtualbox и добавить несколько переменных.
VBOXAUTOSTART_DB, который содержит абсолютный путь к каталогу базы данных автозапуска и
VBOXAUTOSTART_CONFIG, который содержит расположение настроек конфигурации автозапуска. Файл должен выглядеть примерно так:
Теперь нам нужно создать /etc/vbox/vbox.cfg файл и добавить
Примечание: если имя файла vbox.cfg выше не работает, попробуйте назвать autostart.cfg ,
Если вы единственный пользователь, вы можете просто добавить строку default_policy = allow к vbox.cfg файл.
Установите права доступа к каталогу для группы vboxuser и убедитесь, что пользователи могут писать в каталог, а также прикреплять биты.
Добавьте каждого пользователя в vboxusers группа.
(заменить USERNAME с именем пользователя)
ПРИМЕЧАНИЕ. Если вы изменили разрешения группы для текущего пользователя, выйдите из системы и снова войдите в нее, чтобы обновить разрешения. (кредит @ кР105)
Каждый пользователь, который хочет включить автозапуск для отдельных машин, должен указать путь к каталогу базы данных автозапуска с помощью
и включить автозапуск для отдельной виртуальной машины с
Это создаст myuserid.start файл в /etc/vbox каталог
Теперь перезапустите vboxautostart-service, чтобы прочитать изменения.
Перезагрузите систему и ваша виртуальная машина должна запуститься
У меня были похожие несчастные случаи, когда я пытался выполнить эту операцию на ванильном LTS.
В этой версии файл ключа /etc/init.d/vboxautostart-service не был установлен.
Насколько я знаю, все VitualBox и требования были введены с помощью apt-get, поэтому я не могу сказать, почему файл ‘vboxautostart-service’ также не был предоставлен. Но чтобы преодолеть это, вот мое обновление к посту kdmurray.
1) файл / etc / default / virtualbox для меня существовал. Итак, должны добавить переменные:
2) Необходимо создать /etc/vbox/autostart.cfg, как указано в OP.
6б) Нужно получить скрипт vboxautostart-service и сделать его исполняемым.
6c) Оповещение контроллера rc.d, но я использовал 24 в качестве времени запуска. Ставлю только 20 и он не запускается. Возможно, он работал еще до того, как Virtualbox работал.
Затем перезагрузка запустила виртуальную машину правильно.
После многих несчастных часов, пытаясь заставить работать процедуры из kdmurray выше, я безуспешно нашел способ, который работал просто.
Сначала мой хост Linux (Mint 17) был настроен во время загрузки для автоматического входа в мою основную учетную запись.
Во-вторых, я использовал средства VirtualBox GUI (v4.3.12), чтобы создать ярлык для каждой виртуальной машины на рабочем столе.
Далее: я уже обнаружил, что при вызове Меню-> Центр управления -> Запускаемые приложения -> Добавить и добавлении ярлыков на рабочем столе были получены файлы, которые не работали, я заметил из другого ответа на этой странице, что местоположение стартапов — /home/USERNAME/.config/autostart, поэтому я щелкнул правой кнопкой мыши по каждому ярлыку виртуальной машины на рабочем столе, а затем вставил их в эту папку, переписав более ранние файлы дерьма. Теперь они разработали «красивые» иконки VirtualBox.
И, конечно же, при перезапуске хост-компьютера 3 виртуальные машины запускались автоматически.
PS: увы, у меня все еще чего-то не хватает, потому что часто виртуальные машины не запускаются при загрузке, вместо этого они генерируют диалоговое окно с сообщением об ошибке, в котором говорится, что они заблокированы, даже если я сказал им отключиться до перезагрузки хоста.
Источник
Как настроить автозапуск виртуальной машины VirtualBox при включении хоста?
Добрый день
Система: Ubuntu 14.04.2 LTS + VirtualBox 4.3.28
Пользователь запускающий Виртуальные машины: vbox
Виртуальные машины:
Задача: Настроить автозапуск Виртуалки «1C: при запуске хоста. В процессе настройки использую вот этот мануал в котором описываться новые возможности появившиеся в virtualbox 4.2.
Пробовал настроить несколько раз все равно получаю одно и то же:
1 — Как я понимаю когда я пишу команду vboxmanage modifyvm VM_NAME —autostart-enabled on — то в папке VBOXAUTOSTART_DB (/etc/vbox) должен появится файл USERNAME.start. Так вот у меня этот файл появляется только если я выполню команду vboxmanage modifyvm VM_NAME —autostart-enabled on для обеих своих существующих машин. Соответственно когда я запускаю service vboxautostart-service start то он либо ничего не делает (когда файла нет), либо запускает обе машины (когда файл есть), запустить только одну машину у меня не получается.
2 — Если оставить этот файл и перезапустить хост то ни одна из машин всё равно не запустится и их статусы останутся такими, какими были до перезагрузки, то есть получается что даже попыток запустится не происходит.
- Вопрос задан более трёх лет назад
- 13704 просмотра
Не совсем понял как Вы делали, но просто запустить ВМ можно так:
Создать файл
nano /etc/init.d/vm_start.sh
Со следующим содержимым:
Затем сделать скрипт исполняемым и добавить в автостарт:
После рестарта машины запустятся две указанные виртуалки.
Источник
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:
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:
- The name of what I’m using the VM for
- The OS name (Ubuntu, Fedora, FreeBSD, SunOS, MacOS, etc.)
- 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)
- The processor (i86x or amd64)
- 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.
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:
- Machine » Detach GUI
- View » Close VM
- 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.
Источник