How to execute multiple commands with sudo in script [duplicate]
Asked Answered
S

3

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
Scrubber answered 20/5, 2015 at 6:28 Comment(1)
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.Fulviah
C
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
'
Cervantez answered 20/5, 2015 at 6:58 Comment(5)
Could you please help me how it goes when we run it remotelyScrubber
I can try if you specify the problem. What exactly you try to do and how it fails? Run it via ssh?Simpleton
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.Scrubber
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 ;-)Simpleton
Is there any alternative other than adding NOPASSWD to sudoers.Scrubber
J
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.

Jessikajessup answered 20/5, 2015 at 6:45 Comment(0)
M
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)
Manganous answered 20/5, 2015 at 6:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.