0

I need to switch to sudo user and then run a command on remote server using SSH

Actual command

docker stats --no-stream --format  "\"{{ .Name }}\^C{\"memory\":{\"raw\":\"{{ .MemUsage }}\",\"percent\":\"{{ .MemPerc }}\"},\"Node\":\"{{ \"`hostname -i`\" }}\",\"cpu\":\"{{ .CPUPerc }}\"},"

running from ssh also works

ssh 1.2.3.4 'docker stats --no-stream --format  "\"{{ .Name }}\^C{\"memory\":{\"raw\":\"{{ .MemUsage }}\",\"percent\":\"{{ .MemPerc }}\"},\"Node\":\"{{ \"`hostname -i`\" }}\",\"cpu\":\"{{ .CPUPerc }}\"},"'

But when i try to pass it as sudo su - core -c its not working because " pattern matching. How to properly wrap this command ?

sudo su - core -c 'ssh 1.2.3.4 'docker stats --no-stream --format  "\"{{ .Name }}\^C{\"memory\":{\"raw\":\"{{ .MemUsage }}\",\"percent\":\"{{ .MemPerc }}\"},\"Node\":\"{{ \"`hostname -i`\" }}\",\"cpu\":\"{{ .CPUPerc }}\"},"''
1
  • i tried command='docker stats --no-stream --format "\"{{ .Name }}\^C{\"memory\":{\"raw\":\"{{ .MemUsage }}\",\"percent\":\"{{ .MemPerc }}\"},\"Node\":\"{{ \"hostname -i\" }}\",\"cpu\":\"{{ .CPUPerc }}\"}," ';sudo su - core -c 'ssh 1.2.3.4 $command' that didn't work either Commented Mar 10, 2021 at 9:16

1 Answer 1

1

It's simpler with here-document :

sudo su - core << 'END_SUDO'
  ssh self << 'END_SSH'
docker stats --no-stream --format  '"{{ .Name }}{"memory":{"raw":"{{ .MemUsage }}","percent":"{{ .MemPerc }}"},"Node":"{{ "'"$(hostname -i)"'" }}","cpu":"{{ .CPUPerc }}"},'
END_SSH
END_SUDO
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this works. But one problem when I am using ssh -q it still prints banner. Any idea how to supress ssh banner here ?
-q is supposed to suppress most warning and diagnostic messages, not the banner. If you have control on ssh server, you can set PrintMotd=no

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.