IAmYourFaja
IAmYourFaja

Reputation: 56914

How to supply sudo with password from script?

Please note: this is a guest VM (VBox) running on my local machine, and I'm not worried about security.

I am writing a script that will be executed on a Linux (Ubuntu) VM as the myuser user. This script will create a very large directory tree under /etc/myapp. Currently I have to do all this manually, and it starts with me giving myuser recrusive rwx permissions under /etc like so:

sudo chmod -R 777 /etc
[sudo] password for myuser:  <now I enter the password and hit ENTER>

My question: how do I write a bash script that supplies the sudo command with my password so that I can just execute bash myscript.sh and it will make the necessary permission changes for me?

Upvotes: 3

Views: 10946

Answers (3)

AAAfarmclub
AAAfarmclub

Reputation: 2360

(BASH)
OK, if you've gotta do it, (keeping security warnings in mind):

$ sudo -S < <(echo "<your password>") <your sudo command>

Upvotes: 6

Charles Duffy
Charles Duffy

Reputation: 295403

If, as you say, you completely don't care about security...

Run visudo to edit /etc/sudoers with validation in place. Add the following line:

ALL ALL=(ALL) NOPASSWD: ALL

This will prevent sudo from ever asking for a password, for any user, for any command.

Upvotes: 0

salezica
salezica

Reputation: 76929

You can use expect or autoexpect. It's a bad idea, though.

Never put system passwords into writing. At least, not on a file on said system. Much less on an install script known to require root access. You're making yourself an easy target.

What you do instead, is configure sudo via /etc/sudoers/ to allow exactly that user to execute exactly that script without a password:

myuser ALL=(ALL) NOPASSWD : /path/to/script

Note:

  • If you remove the /path/to/script part, myuser will be able to sudo anything with no password.

  • If you change myuser for ALL, everyone will be able to run that script with no password.

Upvotes: 0

Related Questions