Shutdown system in linux

How do I shut down or reboot from a terminal?

Appendix: If your keyboard is «locked up», so you can’t enter a command like «reboot» which would run from «su» anyway, use the keyboard: hold down Alt + PrintScreen/SysRq , buttons and type «REISUB». It doesn’t have to be capital letters. It will restart your computer gently. http://blog.kember.net/articles/reisub-the-gentle-linux-restart/

@NicolasRaoul nopes, for me i see this without sudo . Failed to set wall message, ignoring: Interactive authentication required. Failed to reboot system via logind: Interactive authentication required. Failed to open /dev/initctl: Permission denied Failed to talk to init daemon.

Open your terminal with CTRL + ALT + T and do these following commands

& one more command for restart:

Another way as one of the user mentioned.

You can get more info on the shutdown command by using one of the following:

Can anyone explain why sudo halt might not perform shutdown in some cases, whereas sudo halt -p does?

Hate passwords ( sudo ) and love one-liners?

For Ubuntu 15.04 and later

This is due to Ubuntu’s shift in using systemd instead of Upstart

systemctl poweroff systemctl reboot systemctl suspend systemctl hibernate systemctl hybrid-sleep 

Since hibernate is normally disabled by default in Ubuntu systems, you can enable this by checking this answer.

For Ubuntu 14.10 or earlier

/usr/bin/dbus-send --system --print-reply --dest="org.freedesktop.ConsoleKit" /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Stop 
/usr/bin/dbus-send --system --print-reply --dest="org.freedesktop.ConsoleKit" /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Restart 

Other commands you may like:

/usr/bin/dbus-send --system --print-reply --dest="org.freedesktop.UPower" /org/freedesktop/UPower org.freedesktop.UPower.Suspend 

Hibernate: (if enabled on your system)

/usr/bin/dbus-send --system --print-reply --dest="org.freedesktop.UPower" /org/freedesktop/UPower org.freedesktop.UPower.Hibernate 

On 16.04 no need of sudo

sudo shutdown -h (time) (message) 

This will shutdown your computer and halt it. That is what the -h is for. Then, in the time area you can choose the shutdown delay (in minutes) and if you want you can send a broadcast message in the message area (like goodbye, or I’m shutting the thing down :P).

To restart the computer, type

sudo shutdown -r (time) (message) 

Now, instead of shutting it down and halting it, you will restart your computer once it’s shutdown. 🙂

Источник

Как использовать команду shutdown в Linux с примерами

img

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

Читайте также:  Linux где хранятся сертификаты криптопро

В этом руководстве вы узнаете, как использовать команду выключения Linux shutdown с примерами.

Как использовать команду shutdown в Linux с примерами

Синтаксис команды выключения

Прежде чем переходить к конкретным способам выключения вашей системы Linux, вы должны понять основной синтаксис команды выключения:

shutdown [options] [time] [message]
  • [options] — определяют, хотите ли вы остановить, выключить или перезагрузить машину.
  • [time] — указывает, когда вы хотите завершить выключение.
  • [message] — добавляет сообщение, объявляющее о завершении работы.

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

Для использования команды shutdown в системах Linux требуется пользователь root или пользователь с привилегиями sudo .

Если вы используете команду без дополнительных аргументов, запуск sudo shutdown в окне терминала выполнит завершение работы за 60 секунд.

sudo shutdown

Выключение со всеми параметрами

Чтобы просмотреть все параметры при завершении работы системы Linux, используйте следующую команду:

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

sudo shutdown --help

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

Чтобы запланировать завершение работы, добавьте аргумент [time] и укажите, когда вы хотите, чтобы оно произошло. Есть два способа выключить систему в определенное время — с использованием абсолютного или относительного формата времени.

Абсолютное время соответствует формату чч:мм (hh:mm) и позволяет запланировать выключение в указанное время. Команда следует синтаксису:

Например, чтобы потребовать выключения в 7 утра, введите следующую команду:

sudo shutdown 07:00

В качестве альтернативы можно использовать относительный формат +m и запланировать завершение работы через определенное количество минут с момента запуска команды. В этом случае синтаксис команды:

Чтобы выключить систему через 20 минут, запустите:

sudo shutdown +20

Как немедленно выключить систему

Как упоминалось ранее, запуск команды shutdown без каких-либо аргументов заставляет систему выключиться через минуту после выполнения команды. Однако, если вам требуется немедленное выключение, используйте:

Другой вариант — запланировать выключение, используя формат относительного времени со значением 0, как в приведенной ниже команде:

Как транслировать собственное сообщение

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

Вы можете добавить [message], только если команда также включает атрибут [time]:

sudo shutdown [time] "[message]"

Например, чтобы выключить систему через 20 минут и передать сообщение об обновлении системы, запустите:

sudo shutdown +20 "System Upgrade"

sudo shutdown +20

Как отменить запланированное выключение

Чтобы отменить запланированное выключение, используйте команду:

Вы также можете добавить сообщение для уведомления пользователей об отмене завершения работы. Для этого добавьте параметр [message] (в кавычках) к приведенной выше команде. Например:

sudo shutdown -c "Canceling System Upgrade"

Источник

Linux shutdown command

Computer Hope

On Unix-like operating systems, the shutdown command shuts down or reboots the system.

Description

The shutdown command brings the system down in a secure way. All logged-in users are notified that the system is going down, and login operations are blocked. It is possible to shut the system down immediately, or after a specified delay.

Читайте также:  Восстановление файлов fat linux

All processes are first notified that the system is going down by the signal SIGTERM. This gives programs like vi time to save the file being edited, mail and news processing programs a chance to exit cleanly, etc.

shutdown does its job by signalling the init process, asking it to change the runlevel. Runlevel 0 is used to halt the system, runlevel 6 is used to reboot the system, and runlevel 1 is used to put the system into a state where administrative tasks can be performed (single-user mode). Runlevel 1 is the default, unless the -h or -r options are specified.

Your system may have a different set of options for the shutdown command; check your documentation for details.

Syntax

shutdown [-akrhPHfFnc] [-t sec] time [message]

Options

-a Control access to the shutdown command using the control access file /etc/shutdown.allow. See access control below for more information.
-k Do not shut down, but send the warning messages as if the shutdown were real.
-r Reboot after shutdown.
-h Instructs the system to shut down and then halt.
-P Instructs the system to shut down and then power down.
-H If -h is also specified, this option instructs the system to drop into boot monitor on systems that support it.
-f Skip fsck after reboot.
-F Force fsck after reboot.
-n Don’t call init to do the shutdown of processes; instruct shutdown to do that itself.

The time can be formatted in different ways:

First, it can be an absolute time in the format hh:mm, where hh is the hour (1 or 2 digits, from 0 to 23) and mm is the minute of the hour (in two digits).

Second, it can be in the format +m, where m is the number of minutes to wait.

Details

If a shutdown is scheduled for the future, it creates the advisory file /etc/nologin which causes programs such as login not to allow new user logins. This file is created five minutes before the shutdown sequence starts. shutdown removes this file if it’s stopped before it can signal init (i.e., it is canceled or something goes wrong). It also removes it before calling init to change the runlevel.

The -f flag means «reboot fast». This only creates an advisory file /fastboot which can be tested by the system when it comes up again. The system boot rc file («rc» stands for «runcom», which is short for «run commands») can test if this file is present, and decide not to run fsck since the system was shut down in the proper way. After that, the boot process should remove /fastboot.

The -F flag means «force fsck«. This only creates an advisory file /forcefsck which can be tested by the system when it comes up again. The boot rc file can test if this file is present, and decide to run fsck with a special «force» flag so that even properly unmounted file systems get checked. After that, the boot process should remove /forcefsck.

The -n flag causes shutdown not to call init, but to kill all running processes itself. Shutdown then turns off quota, accounting, and swapping and unmount all file systems.

Access control

shutdown can be called from init when the Ctrl + Alt + Del key combination is pressed, if there exists an appropriate entry in /etc/inittab. This would mean that everyone who has physical access to the console keyboard can shut the system down, however.

To prevent this, shutdown can check to see if an authorized user is logged in. If shutdown is called with the -a argument (add this to the invocation of shutdown in /etc/inittab), it checks to see if the file /etc/shutdown.allow is present. It then compares the login names in that file with the list of people that are logged in on a virtual console (from /var/run/utmp). Only if one of those authorized users or root is logged in, it proceeds. Otherwise, it writes the message

shutdown: no authorized users logged in

. to the (physical) system console. The format of /etc/shutdown.allow is one username per line. Empty lines and comment lines (prefixed by a #) are allowed. Currently there is a limit of 32 users in this file.

Note that if /etc/shutdown.allow is not present, the -a argument is ignored.

Halting vs. powering off

The -H option sets the init environment variable INIT_HALT to HALT, and the -P option sets that variable to POWEROFF. The shutdown script that calls halt as the last thing in the shutdown sequence should check these environment variables and call halt with the right options for these options to actually have any effect.

Files

/fastboot
/etc/inittab
/etc/init.d/halt
/etc/init.d/reboot
/etc/shutdown.allow

Examples

Schedule the system to shut down at 8 A.M.

Schedule the system to shut down at 8 P.M.

shutdown +15 "Upgrading hardware, downtime should be minimal"

Schedule the system to shut down in fifteen minutes. Along with the normal message alerting users that the system is shutting down, they are given the descriptive message about a hardware upgrade.

Bring down the system immediately.

Bring down the system immediately, and automatically reboot it.

Bring down the system immediately, and automatically power off the system.

halt — Stop the computer.
poweroff — Stop the computer.
reboot — Stop the computer.
wall — Send a message to all logged-in users.

Источник

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