2

I have a very long bash script, at the end of it is a command to execute sudo commands on a remote server:

10 hours of local processing
…
ssh user@ip "sudo ls"

I have set up ssh keys to connect to the server and it's working, but it's not enough to run sudo commands. Also because this command is at the end of my script, I don't want to wait for an interactive prompt for the sudo password. Ideally, I would like a prompt for my password at the beginning of the script, store this password in a variable and then pass this variable in my ssh command to execute sudo commands on the remote server.

This is where I'm stuck. I have read countless posts about that but half of them suggest to use this:

ssh $HOST 'echo $PASSWORD | sudo -S $COMMMAND'

which is dangerous since it exposes my password, and half of them suggest to disallow the need for a password for sudo commands on the remote server.

Are these really the only two solutions?

1 Answer 1

1

You can add sudo --validate to the start, it will ask for the password at the start, and cache if for (by default) 15 minutes.

You can edit /etc/sudoers, to add exceptions (commands that can be run without passwords). (This may not be appropriate.)

You could run the whole thing as root, but then drop privileges, and run a sub-shell, the root shell will just wait for the sub-shell to finish, then do its bit.

Add an ssh-key for root, so that you can connect as root.

10
  • The first and last solutions you suggest are not adapted for running sudo on a remote server, am I right? They will allow to run sudo commands on the local but not remote host. As for the second solution, it is not appropriate for me, I have many different sudo commands to run.
    – Sulli
    Feb 17, 2019 at 16:28
  • @Sulli, why are the first and last solutions not adapted for running sudo on a remote server?
    – sudodus
    Feb 17, 2019 at 16:53
  • @sudodus Because sudo --validate will cache the password on the local host but not the remote server? Or should I do something like ssh $host "sudo --validate" then run my commands locally then again ssh $host "sudo my_commands" at the end of my script? Would that work or sudo --validate is only for the current session?
    – Sulli
    Feb 17, 2019 at 16:58
  • 1
    While it was not designed for remote (as is the case with all commands), it makes no difference. You need to run sudo --validate on the same machine/session that you will later run sudo on. Similar for the 3rd option (it all runs on the remote end). Feb 17, 2019 at 16:59
  • Are you saying, that most of the script is running locally, then at the end it connects to the remote, to run one last command with sudo? Feb 17, 2019 at 17:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .