Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script to shutdown/restart Linux system

Tags:

linux

shell

Is there any suitable shell script for shutting down or restarting a Linux machine? I have tried a shell script for shutdown, but when I enter sudo shutdown it will ask for the password. How we can enter the password using the script?

like image 574
Bibin Jose Avatar asked Sep 02 '25 15:09

Bibin Jose


2 Answers

Another, in my opinion cleaner approach:

Create a new file in /etc/sudoers.d/ with content:

%users ALL=NOPASSWD: /sbin/shutdown
%users ALL=NOPASSWD: /sbin/reboot

This causes sudo to not ask for the password, if any user of group "users" tries to execute a shutdown or reboot. Of course you can also specify another group, maybe a newly created group for finer control of reboot permissions.

More information about the other possible settings for sudo can be found in the Manpage.

like image 55
bratkartoffel Avatar answered Sep 05 '25 06:09

bratkartoffel


Yes, use the -S switch which reads the password from STDIN:

$echo <password> | sudo -S <command>

So to shut down the machine, your command would be like this (just replace <password> with your password):

$echo <password> | sudo -S poweroff

Exposing your password is generally bad idea search for something that can protect / hide it. In the past I've used Jenkins plugins to do this while executing the scripts regularly.

like image 43
Wald Avatar answered Sep 05 '25 04:09

Wald