7

Can we use heredocs to run multiple commands using sudo?

I am facing an issue (need to pass password for every command) while running multiple commands:

echo 'password'| sudo -S ls
echo 'password'| sudo -S cat /var/log/abc.log

Can anyone help me how to automate this in a script? Like:

echo 'password' | sudo -S << ENDBLOCK
ls
cat
ENDBLOCK
FormigaNinja
  • 1,571
  • 1
  • 24
  • 36
Sasikiran Vaddi
  • 2,199
  • 4
  • 23
  • 29
  • `sudo` will remember the password used for a short period (5 minutes by default), so there should be no need to supply the password to the second call if the first doesn't take long to run. However, a better solution is to configure `sudo` to allow your specific commands to be run without supplying a password, which keeps the password out of the script altogether. – chepner May 20 '15 at 13:28

3 Answers3

6

you can run sh -c ..., but remember to quote properly.

sudo sh -c 'id; echo another command ; id'

sudo must see this as a single argument for the sh command.

Of course you can use new line instead of semicolon:

sudo sh -c '
  echo "I am root"
  id
  echo "another command"
  id
'
Michał Šrajer
  • 30,364
  • 7
  • 62
  • 85
  • Could you please help me how it goes when we run it remotely – Sasikiran Vaddi May 20 '15 at 07:23
  • I can try if you specify the problem. What exactly you try to do and how it fails? Run it via ssh? – Michał Šrajer May 20 '15 at 07:38
  • In my script, I will login to the VM with sudo user say "sasi" then I need to execute few commands like "mv", "sed" etc. Then I am facing the below issue sudo: no tty present and no askpass program specified Sorry, try again. sudo: no tty present and no askpass program specified Sorry, try again. sudo: no tty present and no askpass program specified Sorry, try again. – Sasikiran Vaddi May 20 '15 at 08:46
  • 1
    sorry for delay. In this situation consider creating script on remote machine to do the job and declare NOPASSWD: tag in /etc/sudoers for this script. You can sudo it then without password. BTW, remember to upvote my answer ;-) – Michał Šrajer May 20 '15 at 13:36
  • Is there any alternative other than adding NOPASSWD to sudoers. – Sasikiran Vaddi May 21 '15 at 05:13
2

One way is to write a script with all the things you need to do with sudo and then run the script with sudo.

thinker
  • 176
  • 3
1

you could put all your commands in a script. Then

  • sudo ./script.sh
  • put permissions for script.sh in /etc/sudoers.d; that way you'll never need to type your password again (for that script)
Chris Maes
  • 35,025
  • 12
  • 111
  • 136