user1767316
user1767316

Reputation: 3631

DIR loop over ssh

logging with ssh to remote server using

ssh [email protected] -i /path/to/ppk.key

then running

[[email protected] ~]$ sudo su - 
[[email protected] ~]# for curdir in $(dir /); do echo "fil=$curdir" ; done

Effectively lists all root directories:

fil=bin
fil=dev
fil=lib

But trying to do it from remote to retrieve result locally is getting tricky to me:

ssh [email protected] -i /drives/c/pass/keys/MY.ppk "sudo -i -u root bash -c 'for curdir in \$(dir \/); do echo "fil=$curdir" ; done'"

give:

fil=var
fil=var
fil=var 
(...)

and

ssh [email protected] -i /drives/c/pass/keys/MY.ppk "sudo -i -u root bash -c 'for curdir in \$(dir \/); do echo "fil=\$curdir" ; done'"

give

fil=
fil=
fil=
(...)

Upvotes: 0

Views: 604

Answers (2)

Barmar
Barmar

Reputation: 780889

Variables inside double quotes are expanded by the local shell, so you need to escape the dollar signs, as in your second version.

Also, double quotes inside the double quotes will terminate the string, you need to escape them as well.

BTW, there's no need to escape /.

ssh [email protected] -i /drives/c/pass/keys/MY.ppk "sudo -i -u root bash -c 'for curdir in \$(dir /); do echo `"fil=\$curdir`" ; done'"

It's often easier to write using a here-doc:

ssh [email protected] -i /drives/c/pass/keys/MY.ppk <<'EOF'
sudo -i -u root bash -c 'for curdir in $(dir /); do echo "fil=$curdir" ; done'
EOF

Putting single quotes around the EOF token treats the here-doc as a single-quoted string, so $ is not treated specially.

Upvotes: 1

Lewis M
Lewis M

Reputation: 548

How about a different approach? You do not need to be root to list out /. So, no need to use sudo or ssh to root. Also, since you really only want to get a listing of / on a remote server, why not just ssh and run the dir command? The loop can then be local. Something like this?

for curdir in $(ssh localhost dir /); do
    echo "fil=${curdir}"
done

Hope this helps

Upvotes: 1

Related Questions