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?
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.If the script is only for personal use and you have placed it in a safe place and you are not afraid of your account being stolen and such, then here's a simple solution:
where LOGINPASSWD is your login password (example: iloveponies) and COMMAND HERE is your command that comes after sudo, like sh -c "echo da.. etc
If you don't mind the script running at a specific time on the hour (or during the day), put it inside root's home directory (
/root
), and run the script from the system crontab (/etc/crontab
) as root. Then you won't have to compromise your security.See https://help.ubuntu.com/community/CronHowto for how to add the script to the crontab.
Another related nice feature of sudo which hasn't been mentioned in the excellent answers above is the 'timestamp_timeout' variable. It is a sudo variable which you may increase to save on interactive password typing.
Example, in /etc/sudoers (or one of the files included from it) you may modify the default:
Full description from 'man sudoers':
Of course, this cannot help in the specific case of running the command from cron. But it is a good thing to be aware of.
To test if it's working type:
To run "sudo apt-get update", and accept password from environment variables what we created before:
Run from python (example changing directory ownership recursively to username_here):
echo $MY_SUDO_PASS get's password -S switch catching it and passing the password to sudo