Запретить запуск Ubuntu до завершения автоматического обновления фона

Вы можете, конечно, использовать Ubuntu, ничего не зная о Linux. Однако, как только вы займетесь этим, вы, скорее всего, захотите узнать больше. Это похоже на переход от старого мула, который не заботится о том, что вы хотите для транспортного средства, которое может быть пикапом или гонщиком Indy или водным мотоциклом, как вы сочтете нужным.

Понемногу вы научитесь делать то, что вас больше всего интересует.

1
задан 25 November 2015 в 03:37

2 ответа

Введение

В приведенном ниже сценарии используется опрос, управляемый прерываниями для определенных сообщений от dbus, и всякий раз, когда он видит запрос на выключение / перезагрузку, он будет проверять, имеет ли диспетчер пакетов, например dpkg или apt работают.

Настроить

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

Ручная настройка

mkdir $HOME/bin Скопируйте источник сценария, сохраните его в файл с именем preventShutdown.sh. Сценарий должен быть исполняемым. Используйте chmod +x $HOME/bin/preventShutdown.sh для этого. Добавьте сценарий в список подпрограмм, которые будут запускаться при входе в Unity / Gnome, используя приложение «Запуск приложений» или вручную помещая файл .desktop в $HOME/.config/autostart

Альтернативная настройка [ ! d10]
sudo apt-get install git
cd /opt
sudo git clone https://github.com/SergKolo/sergrep.git
sudo chmod +x /opt/sergrep/*

Добавить скрипт в качестве загрузочного приложения.

Источник скрипта

#! /bin/bash

##########################
# AUTHOR: Serg Kolo 
# Date: Saturday, December 26th, 2015
# Description: Script to notify user and prevent 
#   shutdown or reboot
#   if any update or package manager
#   are running. 
# TESTED ON: 14.04.3 LTS, Trusty Tahr
# WRITTEN FOR: http://askubuntu.com/q/702156/295286
# VERSION: 2, removed xdotool, using dbus method
#          changed to C-style of organizing code
#########################

# Copyright (c) 2015 Serg Kolo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal in 
# the Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 
# the Software, and to permit persons to whom the Software is furnished to do so, 
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all 
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Uncomment the line bellow if needed for debugging
# set -x
###########################
# VARIABLES
###########################

DISPLAY=:0 # has to be set since we are using notify-send


###########################
# MAIN
###########################
#
#    Basic idea : This runs dbus-monitor which waits for
# "RebootRequested" memberf from com.canonical.Unity.Session ,
# which apprears only when the user clicks the shutdown option 
# from the Unity's top right drop down box. Why RebootRequested ?
# Because this message is guaranteed to pop up once user presses
# the shutdown button.
#   The while loop with read command does the big job.
# dbus-monitor sends initial message , so we want to filter only
# The output that contains the string we need, hence the case...esac
# structure employed here. Once we get the proper message.
# we check whether update-manager or package managers are running
# If there is one instance, then call CancelAction method
# and send notification to the user.
#   Both dbus-monitor and while loop run continuously. This
# can be launcher as script in `/etc/rc.local` or `/etc/rc2.d`
# or preferably (!) in `/etc/xdg/autostart/` . 
#   Here is sample /etc/xdg/autostart/preventShutdown.desktop file
# 
# [Desktop Entry]
# Type=Application
# Name=Prevent-Update
# Exec=/home/$USER/bin/preventShutdown.sh
# OnlyShowIn=GNOME;Unity;
# Terminal=false
# 
# Remember to make this file  as well as script be root-owned with 
# chmod +x /path/to/Script.
# It is preferred to store the script in user's personal $HOME/bin
# folder.
# Make sure to edit $HOME/.profile file to include that into $PATH
# variable

interupt()
{
 qdbus com.canonical.Unity /com/canonical/Unity/Session com.canonical.Unity.Session.CancelAction
 notify-send "<<< UPDATE IN PROGRESS; DO NOT SHUT DOWN>>>"
 wall <<< "<<< UPDATE IN PROGRESS; DO NOT SHUT DOWN>>>"
}

main()
{
 dbus-monitor --profile "interface='com.canonical.Unity.Session',type=signal" |
 while read -r line;
 do
  case "$line" in
   *RebootRequested*)
       pgrep update-manager || pgrep apt-get || pgrep dpkg
    if [ $? -eq 0 ]; then
           interupt
        fi
     ;;
   esac
 done
}

main
7
ответ дан 23 May 2018 в 15:31
  • 1
    +1: Это именно то, что я собирался сделать в сценарии, но я быстро понял, что это намного сложнее, чем я подозревал. – cat 28 December 2015 в 03:13
Чтобы процитировать Эйнштейна:
Only two things are infinite, the universe and human stupidity, 
and I'm not sure about the former.
, поэтому нет 100% -ной гарантии от человеческой глупости, но вы можете усложнить не-Einsteins, чтобы сломать вещи: Активация автоматических обновлений при выключении. Объясните, что компьютеры - это не молотки, ни гвозди, а хрупкие интеллектуальные части оборудования, которые нуждаются в двух видах пищи: электричестве и обновлениях.

В качестве альтернативы,

Чтобы процитировать Эйнштейна:
Only two things are infinite, the universe and human stupidity, 
and I'm not sure about the former.
, поэтому нет 100% -ной гарантии от человеческой глупости, но вы можете усложнить не-Эйнштейны, чтобы сломать вещи by:
Попросите пива или приятную еду, чтобы «настроить» компьютер

Альтернативно: • используйте Remmina для бесперебойной работы

5
ответ дан 23 May 2018 в 15:31
  • 1
    100% согласились. Также он мог настроить передачу ssh и портов на маршрутизаторе, чтобы управлять им удаленно. – Sergiy Kolodyazhnyy 26 December 2015 в 15:38
  • 2
    Меньше сексизма было бы хорошо. – LovesTha 1 January 2016 в 07:19
  • 3
    @LovesTha какой сексизм? – Fabby 20 March 2018 в 18:19
  • 4
    Через 8 часов после того, как я оставил этот комментарий, вы отредактировали сообщение, чтобы быть намного менее сексистским. Теперь через два года у вас возникли проблемы с напоминанием о том, что вы изначально писали. – LovesTha 22 March 2018 в 15:30
  • 5
    @LovesTha Да, не сексист больше ... Время, чтобы удалить комментарий. :-) – Fabby 25 March 2018 в 22:11

Другие вопросы по тегам:

Похожие вопросы: