shell script to shutdown/restart Linux system

2019-06-04 07:09发布

问题:

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?

回答1:

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

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

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.



回答2:

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.



回答3:

if you really want to achieve it, you should write a script containing the shutdown command; make root be its owner, then set the SUID bit with the chmod command and give to it executable permission for everybody. When executed, the owner of the script would become root and no password should be asked.



标签: linux shell