How do I sudo a command in a script without being asked for a password?

249,234

Solution 1

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.

Solution 2

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

Solution 3

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.

Solution 4

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.

Solution 5

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

Share:
249,234

Related videos on Youtube

Viswa
Author by

Viswa

Updated on September 18, 2022

Comments

  • Viswa
    Viswa almost 2 years

    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?

    • Alex Hirzel
      Alex Hirzel about 12 years
      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.
  • Anwar
    Anwar about 12 years
    @Viswa, Please note that, this is very very dangerous to reveal password in plain text. You are highly advised ,not to do that
  • balki
    balki about 12 years
    You might probably want to use anacron if that is a desktop/laptop which don't run 24x7
  • ArtOfCode
    ArtOfCode about 12 years
    Such a well detailed, helpful answer and exactly how it should be done.
  • ish
    ish about 12 years
    @RobertRosati, many thanks for your suggested edit -- I shouldn't have forgotten that in the first place!
  • Bryce
    Bryce about 12 years
    -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.
  • Viswa
    Viswa about 12 years
    thanks, But now i knew how to run the sudo command without asking password. At the same time i understood the problems with reveal password.
  • AmazeCPK
    AmazeCPK almost 12 years
    Downvoted, this is the Road to the dark side, and not needed with the sudo method.
  • hytromo
    hytromo almost 12 years
    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 ??
  • m-ric
    m-ric over 11 years
    Are chmod and chown really needed?
  • Tobias Kienzler
    Tobias Kienzler over 10 years
    @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"
  • Bee
    Bee over 10 years
    I tried to do this. #!/usr/bin/env python _ import os _ os.system('sudo bash /apps/myapp') but now my python script asks for password. :( Why is that?
  • Rab
    Rab over 9 years
    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
  • NVRAM
    NVRAM over 8 years
    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.
  • Elder Geek
    Elder Geek over 6 years
    I'm not sure what this adds to the existing answers most current BIOS support wake on alarm...
  • traducerad
    traducerad over 6 years
    Hi, I need to open this file "/dev/input/event3". I do this by doing "open(myfile, "r")" in python. Issue is that -as you guessed- I need elevated privileges to read this file. Besides this I can't put this single line of code in a separate file which I then add to visudo, because I need to continuously read this file's content. What would you suggest?
  • Sun Bear
    Sun Bear over 5 years
    Can you explain what date '+%s' -d '+ 24 hours' do in wakealarm file? This link explains what wakealrm does. Does this procedure works for Ubuntu 16.04 systems and greater?
  • HappyFace
    HappyFace almost 5 years
    This is the best answer here. Not for this specific question but for the general question of running sudo non-interactively.
  • Shiva
    Shiva over 3 years
    I needed to start another process as superuser in a separate terminal window and let it run in the background. Instead of entering the password in plain text, I got it from the prompt using getpass.getpass(), and it worked like a charm. Thanks!