Ubuntu – How to sudo a command in a script without being asked for a password


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

Please note: Any method which involves putting your login password in plain text, in a command or in a file, is insecure and should NOT be used!

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

  • Open up gedit (or your favorite editor), and create the script e.g. pydatertc.sh
  • Insert only this line, and save it to, e.g. your home directory:
    echo date \'+%s\' -d \'+ 24 hours\' > /sys/class/rtc/rtc0/wakealarm
  • Quit the editor, and from the terminal, make the script executable and change its ownership to root, otherwise another user with access to your system could possibly edit it and execute whatever commands they want as root without needing your password:
    sudo chown root:root /home/username/pydatertc.sh
    sudo chmod 700 /home/username/pydatertc.sh

Step 2. Set up sudo to allow pydatertc.sh to execute without requiring a password

  • Type sudo visudo at the terminal to open the sudo permissions (sudoers) file
  • Around line 25, you'll see this line: %sudo ALL=(ALL:ALL) ALL
  • Below that line, insert the following line, where username is your username:
    username  ALL=(ALL) NOPASSWD: /home/username/pydatertc.sh
  • Exit the editor (Ctrl+X if nano)

Step 3. Modify your python script to call pydatertc.sh

  • Change the line to:
    os.system('sudo /home/username/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 with chown (if you are the only user setting the alarm), or make it world-writeable with chmod +666; in that case, simply remove the sudo from your Python call, leaving sh -c "...." intact.