Alternative way to run a sudo command on startup
I am trying to write a script for my Ubuntu system to hibernate, whenever the amount of battery left is (say) 5%. This script will run on startup.
I can get the battery left using
upower -d |grep perc
Then I wish to use
sudo pm-hibernate
whenever battery reaches <= 5%. But this requires superuser permission. AND I DON'T WANT TO TYPE PASSWORD AGAIN AND AGAIN AFTER EVERY LOGIN.
One way is to use add the following line in /etc/sudoers
yourlogin ALL=(ALL) NOPASSWD: command_here
But most people recommend against that.
Another way is to add a custom startup script in /etc/init.d
. But I am not sure whether it is a safe choice.
Also, is there any other alternative which would be best for my purpose?
Solution 1:
Simpler than adding a script to init.d
is to write an Upstart configuration. I'd favour this above all. Create a .conf
file in /etc/init
(say /etc/init/sleep-on-suspend.conf
, containing:
description "Automatic suspend"
start on runlevel [2345]
stop on runlevel [016]
exec /path/to/script
This will be automatically started on reboot.
You could even integrate the script into this file. Instead of the exec
line, use:
script
while sleep 1; do
upower -d | awk -F'[ %]*' '/perc/ && ($3 < 5) { exit 1 }' || pm-hibernate
done
end script
Solution 2:
Run sudo crontab -e -u root
and append the line @reboot /path/to/script
to the bottom of the file, then the root user will automagically run your script as root on login. And a friendly reminder to make sure nobody apart from you and root can access the script, otherwise people could run any command as root.
Solution 3:
This script will run on startup.
If you really mean this then you are already talking root privileges.
What does the rest of your script look like? We can't really judge the security or lack of same from isolated commands.
One alternative would be to run it, say, every 5 minutes out of root
's crontab
. If you are scared of security consequences, you could create a dedicated user who has limited privileges except within power management.
Add this to a new file:
*/5 * * * * root /usr/local/sbin/hibernate-on-power-low
(where maybe root
could be replaced with a dedicated user if you like) and install this in /etc/cron.d/hibernate-maybe
. Obviously, the script which does the real work would have to be installed in /usr/local/sbin/hibernate-on-power-low
and properly audited for security and efficiency (probably using a direct kernel interface would be more robust and efficient than grep
) and obviously, if you run with adequate privileges already, you don't need sudo
to run pm-hibernate
.