I have a issue with for loop. Will brief it out for you.
$ for i in `cat serverss`;do ssh -q $i sudo echo "a b c" > /tcb/files/auth/x/xyz;done
ksh: /tcb/files/auth/x/xyz: cannot create
I am getting above error whenever i try to create or modify a file. serverss is the file file which has list of servers.We have sudo to root on those systems.
The problem is when i run echo "a b c" > /tcb/files/auth/x/xyz
on individual servers it runs perfectly. What is the issue in my for loop which throws me the above error.
There are two issues here:
/tcb/files/auth/x/xyz
locally, not on the remote system.sudo echo foo > bar
does not provide extra privileges to help in opening bar
.This latter is because something > output
opens output
before it runs something
. Thus, sudo
hasn't even been started when /tcb/files/auth/x/xyz
is opened!
Instead, consider:
ssh -q "$i" 'echo "a b c" | sudo tee /tcb/files/auth/x/xyz >/dev/null'
The first problem is solved because the redirection is inside the string passed to ssh
to be run by a remote shell. (If you pass ssh
a bunch of separate arguments, it just combines them with spaces to form such a string; it's better to form the string yourself, and thereby have more control).
The second problem is solved by forcing /tcb/files/auth/x/xyz
to be opened by tee
, after tee
has had its privileges escalated by sudo
.