Linux – How to use ssh and sudo together in bash

bashlinux

I haven't been able to find a question that describes this specific scenario.

I am trying to execute a very basic bash script to retrieve logging from multiple machines. I am running the script locally but need to access an external machine via ssh, as well as sudo into a privileged user once on that machine…

ssh myuser@machine.net
sudo su  - privledged_user
cat logs > file.txt

Running this with sh -x reveals bash is getting stuck on the 'ssh' line. So I tried revising it to this:

ssh myuser@machine.net sudo su - privledged_user cat logs > file.txt

This also seems to stall indefinitely. Is there a better solution to this problem?? I don't see a way around using sudo su from what I can tell…

Thanks for any help!

Best Answer

The way I achieve this in my current environment, is to run ssh with the -t flag which forces tty allocation, and to then run sudo -u root within it, as follows:

ssh -t hostname << EOF
  command1
  sudo -u root command2
  sudo -u otheruser "command3 | command4"
  sudo -u root /bin/bash -c "command5; command6; command7"
  command8 && ( sudo -u otheruser /bin/bash -c "cmd1 ${1}; cmd2 {$2}" ) || echo cmd2 did not work

EOF

I have my account in sudoers on the remote side so that no password is required.

This example shows you different ways to do this within a single ssh session, including running multiple commands with bash or within a subshell. Note also that if you put the above code into an executable script, you can pass command line arguments ($1 and $2) to ssh and these will be expanded and then referenced on the remote side.