Use sudo with password as parameter

LinuxBashSudo

Linux Problem Overview


I would like to run sudo with my password as parameter so that I can use it for a script. I tried

sudo -S mypassword execute_command

but without any success. Any suggestions?

Linux Solutions


Solution 1 - Linux

The -S switch makes sudo read the password from STDIN. This means you can do

echo mypassword | sudo -S command

to pass the password to sudo

However, the suggestions by others that do not involve passing the password as part of a command such as checking if the user is root are probably much better ideas for security reasons

Solution 2 - Linux

You can set the s bit for your script so that it does not need sudo and runs as root (and you do not need to write your root password in the script):

sudo chmod +s myscript

Solution 3 - Linux

echo -e "YOURPASSWORD\n" | sudo -S yourcommand

Solution 4 - Linux

One option is to use the -A flag to sudo. This runs a program to ask for the password. Rather than ask, you could have a script that just spits out the password so the program can continue.

Solution 5 - Linux

# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionccmanView Question on Stackoverflow
Solution 1 - Linuxstonesam92View Answer on Stackoverflow
Solution 2 - LinuxperrealView Answer on Stackoverflow
Solution 3 - LinuxmatteomatteiView Answer on Stackoverflow
Solution 4 - LinuxLucas HoltView Answer on Stackoverflow
Solution 5 - LinuxkbdjockeyView Answer on Stackoverflow