How to use ssh and sudo together in bash?
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 [email protected]
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 [email protected] 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!
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.
If you don't want or can't stop sudo from asking you the password, one simple trick is to read it locally and store it in a local variable:
read -p 'Password: ' -s password
ssh -t [email protected] <<EOF
echo "$password" | sudo -S whoami
EOF