125

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?

1
  • 4
    You should look in your motherboard manual or BIOS to see if it supports this behavior. I know it dodges the question! =] But it may be a sufficient solution. Jun 25, 2012 at 19:22

6 Answers 6

178

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.

9
  • 1
    Awesome, this is the correct way to do it.
    – roadmr
    Jun 25, 2012 at 15:14
  • 1
    Such a well detailed, helpful answer and exactly how it should be done.
    – ArtOfCode
    Jun 25, 2012 at 15:50
  • @RobertRosati, many thanks for your suggested edit -- I shouldn't have forgotten that in the first place!
    – ish
    Jun 25, 2012 at 16:48
  • 1
    @m-ric Did you read the command above these lines? "otherwise another user with access to your system could possibly edit it and execute whatever commands they want as root without needing your password" Nov 18, 2013 at 13:12
  • 5
    I realize this answer is old -- but there's still a problem here: if the file is located in /home/username, then the system can be compromised if that directory is writable by a malicious user (or a non-root login that is compromised). They could remove or rename the file, put another script in its place, and running that script via sudo -- without a password. Hence, it's far safer to put the script to a directory that only root can alter, eg: /usr/sbin or /root. Otherwise, it LGTM.
    – NVRAM
    Jan 10, 2016 at 19:14
33

Warning!

Putting your login password in plain text, in a command or file, is extremely insecure and can compromise your private data and your system. It is highly recommended never to do this even if you think your system is "personal" or in a "safe location"!

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:

echo LOGINPASSWD | sudo -S COMMAND HERE

where LOGINPASSWD is your login password (example: iloveponies) and COMMAND HERE is your command that comes after sudo, like sh -c "echo da.. etc

8
  • 15
    @Viswa, Please note that, this is very very dangerous to reveal password in plain text. You are highly advised ,not to do that
    – Anwar
    Jun 25, 2012 at 15:04
  • 3
    -1 If this seems like a good idea, you'd be way better off just set a password on your root account and use z7sg's solution; that's just as easy, and doesn't create this very dangerous security issue.
    – Bryce
    Jun 26, 2012 at 2:04
  • 4
    Hah! I had 6 upvotes and 4 downvotes on my answer :) But why guys, wasn't I clear 'Personal use', 'safe place' etc? There isn't a security issue unless you give this file out and you have an ssh server running! Where do you see the security issue provided that the script is for personal use and in safe place?
    – hytromo
    Jun 26, 2012 at 10:32
  • 6
    Downvoted, this is the Road to the dark side, and not needed with the sudo method.
    – Floyd
    Jul 28, 2012 at 6:11
  • 4
    Ok, just tell me, even if the hacker has logged in as simple user to your account, how the heck will he find the script with your password under /usr/share/help/lv/ubuntu-help ??
    – hytromo
    Jul 28, 2012 at 8:45
20

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.

2
  • 4
    You might probably want to use anacron if that is a desktop/laptop which don't run 24x7
    – balki
    Jun 25, 2012 at 15:23
  • This is a useful answer, for example if you are writing the script to check for updates, do something with that information, and email the administrator about updates needed. Personally, many of my scripts are used for server automation, so just using sudo crontab -e is what I would tend to do. +1
    – Rab
    Oct 17, 2014 at 23:50
11

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:

# only require a password once every 60 minutes
Defaults timestamp_timeout=60

Full description from 'man sudoers':

timestamp_timeout

        Number of minutes that can elapse before sudo will ask for
        a passwd again.  The default is 5, set this to 0 to always
        prompt for a password.

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.

1
export MY_SUDO_PASS="user_password_here"

To test if it's working type:

echo $MY_SUDO_PASS
> user_password_here

To run "sudo apt-get update", and accept password from environment variables what we created before:

echo $MY_SUDO_PASS | sudo -S apt-get update

Run from python (example changing directory ownership recursively to username_here):

python
>> import subprocess
>> subprocess.call('echo $MY_SUDO_PASS | sudo -S chown -R username_here /home/username_here/folder_to_change_ownership_recursivley', shell=True)

echo $MY_SUDO_PASS get's password -S switch catching it and passing the password to sudo

2
  • I'm not sure what this adds to the existing answers most current BIOS support wake on alarm...
    – Elder Geek
    Mar 15, 2018 at 17:12
  • Hey there, II tried this solution. It works with the terminal but not when I run the python script. the $MY_SUDO_PASS variable isn't stored with python script
    – ARRAFI
    Dec 27, 2023 at 11:39
0

Borrowing code from @jturi's solution, I tweaked the code a bit to make it work. Previously, when running from the python script the password variable wasn't being stored, so I stored it as an environment variable.

import subprocess
import os

# Set the environment variable
os.environ['MY_SUDO_PASS'] = 'your_sudo_password'

# Display the environment variable
subprocess.call('echo $MY_SUDO_PASS', shell=True)

# Run the command with sudo
subprocess.call('echo $MY_SUDO_PASS | sudo -S ls', shell=True)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .