ashrufr
ashrufr

Reputation: 13

ssh remote command as different user

Why does the awk portion of this command not get processed. It works when I run this directly as user1.

[zimmerman@SERVER1 check]# su  user1 -c "ssh -i /home/user1/.ssh/id_rsa -q user1@SERVER2 df -h /dir1/dir2 | awk '{print $5}'"

Filesystem            Size  Used Avail Use% Mounted on
/dev/sdf1            1008G  204M  957G   1% /dir1/dir2

Upvotes: 1

Views: 194

Answers (1)

Jakuje
Jakuje

Reputation: 26016

When you combine all these stuff together, you need to make sure you escape all the important characters that you don't want to evaluate now, but later one. The $ is a good example of that.

$ su user1 -c "ssh -i [...] -q user1@SERVER2 df -h /dir1/dir2 | awk '{print $5}'"

evaluates the $5 in the current bash, which is what you don't want. You can see it, if you run simply

$ echo "ssh -i [...] -q user1@SERVER2 df -h /dir1/dir2 | awk '{print $5}'"
ssh -i [...] -q user1@SERVER2 df -h /dir1/dir2 | awk '{print }'

So to fix it, you need to escape the $ sign, such as

$ echo "ssh -i [...] -q user1@SERVER2 df -h /dir1/dir2 | awk '{print \$5}'"
ssh -i [...] -q user1@SERVER2 df -h /dir1/dir2 | awk '{print $5}'

TL;DR: so the final commandline you should use is

su  user1 -c "ssh -i /home/user1/.ssh/id_rsa -q user1@SERVER2 df -h /dir1/dir2 | awk '{print \$5}'"

Upvotes: 1

Related Questions