I want to turn my system on automatically every day. So I use the below code in my Python script, but sudo
asks me for a password every time:
os.system('sudo sh -c "echo date \'+%s\' -d \'+ \
24 hours\' > /sys/class/rtc/rtc0/wakealarm"')
How can I run this script without sudo
asking for the password every time?
Best Answer
The correct way to do it to setup
sudo
such that only the one specific command you need, i.e.echo date... > rtc...
, is allowed to run WITHOUT needing the password.Step 1. Create a shell script with just that command
gedit
(or your favorite editor), and create the script e.g.pydatertc.sh
Step 2. Set up sudo to allow
pydatertc.sh
to execute without requiring a passwordsudo visudo
at the terminal to open the sudo permissions (sudoers
) file%sudo ALL=(ALL:ALL) ALL
username
is your username:Step 3. Modify your python script to call
pydatertc.sh
Now your script should run without requiring a password AND without compromising the security of your account, your data or your system!
Alternative only for
wakealarm
(not for general use!):In this specific case only, since the
/sys/class/rtc/rtc0/wakealarm
file only controls the wake-up alarm for the system and is otherwise harmless, another alternative to avoid the password is either to take ownership of that file withchown
(if you are the only user setting the alarm), or make it world-writeable withchmod +666
; in that case, simply remove thesudo
from your Python call, leavingsh -c "...."
intact.