Linux reboot to windows

Как перезагрузиться в Windows из Ubuntu?

Я ищу способ перезагрузки в Windows из Ubuntu в системе с двойной загрузкой 10.10 / Vista. Конкретный вариант использования заключается в том, что я хотел бы иметь возможность подключиться по ssh к моему работающему экземпляру Ubuntu и выполнить команду, которая инициирует перезагрузку непосредственно в Windows.

Я нашел многообещающее сообщение в блоге , но предлагаемый сценарий не работает:

#!/bin/bash WINDOWS_ENTRY=`grep menuentry /boot/grub/grub.cfg | grep --line-number Windows` MENU_NUMBER=$(( `echo $WINDOWS_ENTRY | sed -e "s/:.*//"` - 1 )) sudo grub-reboot $MENU_NUMBER sudo reboot 

man grub-reboot не сильно помогает, но, похоже, ведет меня в правильном направлении:

устанавливает загрузочную запись по умолчанию для GRUB, только для следующей загрузки

WINDOWS_ENTRY=`grep menuentry /boot/grub/grub.cfg | grep --line-number Windows` MENU_NUMBER=$(( `echo $WINDOWS_ENTRY | sed -e "s/:.*//"` - 1 )) echo $MENU_NUMBER 

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

8 ответов

sudo gedit /etc/default/grub 

alt text

  • Ищите строку GRUB_DEFAULT=0 и измените ее на GRUB_DEFAULT=saved
  • Обновите grub следующей командой.
     sudo gedit switch-to-windows.sh 
    #!/bin/bash WINDOWS_ENTRY=`grep menuentry /boot/grub/grub.cfg | grep --line-номер Windows`. MENU_NUMBER=$(( `echo $WINDOWS_ENTRY | sed -e "s/:.*//" ` - 1 )) sudo grub-reboot $MENU_NUMBER перезагрузка с нуля 
     sudo chmod +x switch-to-windows.sh 

    alt text

    • Если это ваше меню grub и если вы хотите загрузиться в окна, то вы должны указать значение X как 5.
    • sudo grub-reboot 5
    • Вы также можете создать пусковую установку для вышеуказанной команды, так что двойной щелчок по пусковой установке перезагрузится в windows.

    Для этого есть команда grub-reboot grub-reboot .

    Похоже, что она работает только в том случае, если у вас настроен grub на начало работы с последней сохраненной записью. Так что если вы ещё этого не сделали, измените /etc/default/grub и установите

    , затем обновите файл конфигурации grub:

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

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

    , где ENTRY может быть числом относительно пункта меню (пронумерованным, начиная с 0), или точным заголовком пункта меню, например

    sudo grub-reboot "Microsoft Windows XP Professional (on /dev/sda1)" 

    Эта команда может быть легко доступна как пусковая установка

    #!/usr/bin/env xdg-open # # save as ~/Desktop/reboot-into-windows.desktop # [Desktop Entry] Version=1.0 Type=Application Terminal=false Exec=sh -c 'gksu "grub-reboot 2" && gnome-session-save --shutdown-dialog' Name=Reboot into Windows Icon=gnome-panel-launcher 

    , но я не знаю, как она может быть интегрирована в системное меню.

    Читайте также:  Computers using linux os

    Вы можете получить доступное заглавие пункта меню с помощью

    sed -n '/menuentry/s/.*\(["'\''].*["'\'']\).*/\1/p' /boot/grub/grub.cfg 

    Насколько я понял, это будет не совсем то, что вы хотите, но я думаю, что это довольно близко. Просто перейдите по ссылке webupdate article.

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

    Решение по перезагрузке в конкретную систему, выбранную через единую пусковую установку, было только что размещено на webupd8. Смотрите http://www.webupd8.org/2011/05/custom-unity-launcher-to-reboot-in.html

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

    Просто отредактируйте /boot/grub/grub.cfg и измените запись по умолчанию, чтобы она указывала на запись, которую вы хотите загрузить. Значение может быть либо порядковым номером записи (начиная с нуля для первой), либо вы можете поместить полное название нужной записи в кавычки.

    Не уверен, что это на 100% сработает и в убунту, но я однажды сделал эту работу на центробежной машине

    , в основном, вам придется сказать grub.conf, какой id # из grub.conf должен запуститься следующим. ID # можно узнать по

    echo `sudo grep ^title /boot/grub/grub.conf | grep -n Windows | cut -f 1 -d:`-1 

    так что в моем случае это будет, например, вывод «4-1», так как четвертая запись в моем grub.conf содержит текст «Windows». (Замените это на фактическое имя записи (также частично), которое вы хотите использовать. Тогда вы можете скормить это в grub как:

    echo "savedefault --stage2=/boot/grub/stage2 --default=4-1 --once" | sudo /sbin/grub 

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

    это все может быть объединено в скрипт типа:

    #!/bin/sh let NEWBOOT=`sudo grep ^title /boot/grub/grub.conf | grep -n Windows | cut -f 1 -d:`-1 echo Booting $NEWBOOT - `sudo grep ^title.\*Windows /boot/grub/grub.conf` echo "savedefault --stage2=/boot/grub/stage2 --default=$NEWBOOT --once" | sudo /sbin/grub sudo reboot 

    скрипт автоматически определит, какой элемент из вашего grub.conf соответствует тексту «Windows», будет кормить это в grub, чтобы сказать, что должно быть загружено при следующей загрузке и перезагрузит ваш компьютер

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

    Источник

    Creating a «Reboot into Windows» Button in Ubuntu

    If you’re dual booting a Windows and Ubuntu desktop, it can feel a bit cumbersome having to wait for GRUB and then manually choosing to boot into Windows. There is a utility packaged with GRUB which can help resolve this, but it requires a bit of setup.

    Читайте также:  Linux get all users and groups

    I have used this solution successfully on both Ubuntu 16.04 and 18.04. There is no reason that this solution should not work on any other distribution that is using GRUB, but without testing, I cannot say with absolute certainty!

    Updating The GRUB Configuration

    The first step, is to update the GRUB configuration. In Ubuntu, this file can be found at /etc/default/grub .

    Assuming this file has not been modified already, there should be a variable assignment that reads:

    Comment out this line, and replace it with:

    Changing The Timeout (Optional)

    In addition to this, I also commented out the GRUB_HIDDEN_TIMEOUT and GRUB_HIDDEN_TIMEOUT_QUIET options and set the GRUB_TIMEOUT option to a value of 3 .

    This change makes GRUB boot the highlighted system after 3 seconds if the user does not interact with the GRUB menu (i.e. by changing the selected menu item).

    Once the changes are made, you should have a GRUB file that resembles this in some form:

    /etc/default/grub

    Applying The GRUB Updates

    Once the changes have been saved to /etc/default/grub , run:

    This will update the GRUB menu entries and update the active configuration file.

    Creating The Script

    Now that GRUB is configured, the script that will be invoked by the shortcut can be created.

    Firstly, the name of the menu entry must be confirmed. To do this, run:

    grep -i windows /boot/grub/grub.cfg 

    You should see output akin to the below:

    In this screenshot, the menu entry name would be the text that is enclosed within the single quotation marks; i.e. Windows Boot Manager (on /dev/nvme0n1p1) — take note of the value that you see.

    Next, create the reboot script — for this example, we’ll place it in /opt/reboot-into-windows . Populate the file with the following contents:

    #!/bin/bash /usr/sbin/grub-reboot "Windows Boot Manager (on /dev/nvme0n1p1)" /sbin/reboot 

    As can be seen above, the value found when using grep has been used as the argument for grub-reboot — make sure you replace this with the value that you identified in the previous step.

    Lastly, ensure that the script is executable and only writable by the root user by running:

    sudo chown root:root /opt/reboot-into-windows sudo chmod 755 /opt/reboot-into-windows 

    N.B. it’s very important that only root can write to this file, so don’t skip this step.

    Читайте также:  Автомонтирование сетевых папок astra linux

    Setting Up The Shortcut

    Before creating the shortcut, there is one last step that needs to be carried out, and that is allowing the script to be executed using sudo, without a password.

    To do this, run the following command, ensuring to replace YOUR_USERNAME with the user you will be logged in as:

    sudo echo 'YOUR_USERNAME ALL=(ALL) NOPASSWD: /opt/reboot-into-windows' > /etc/sudoers.d/00-windows-reboot 

    Important Note: Under no circumstance should you change the above to allow all commands to be run using sudo with no password. This should be limited strictly to /opt/reboot-into-windows and only root should have write permissions to the file. If you do not follow these steps explicitly, you will be lowering the security of your system.

    Once the sudoers file has been setup, you can create the shortcut. To do this, create another new file on your desktop (name it whatever you wish), containing the following content:

    #!/bin/bash sudo /opt/reboot-into-windows 

    Ensure the file is executable by running:

    chmod +x ~/Desktop/THE_NAME_OF_YOUR_FILE 

    Lastly, if you want, you can add an icon to this file by right clicking it, and clicking Properties and then left clicking on the current icon. I used the following Windows 10 icon:

    The setup of the shortcut is now complete, and after double clicking should reboot your machine into Windows!

    On Ubuntu 18.04, an extra step seems to be necessary, which is setting the default behaviour for executable text files. To do this, open Nautilus (the file explorer), and in the top bar, drop down the “Files” menu and click “Preferences”.

    In the window that appears, go to “Behaviour” and ensure that the “Executable Text Files” setting is either “Run Them” or “Ask what to do”.

    If you choose “Ask what to do”, as the setting suggests, you will be prompted every time whether you want to view the file or execute it.

    The end result should be something that looks like this:

    It should also be noted, clicking the “Reboot into Windows” button will not make it the permanent default. It will only set it as the default selection for that individual reboot; meaning the next time you boot the machine, it will boot into Ubuntu as usual!

    Источник

  • Оцените статью
    Adblock
    detector