Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to assign a list of remote authorized keys files to a local variable.

INCLUDE=$(ssh "for Z in `awk -F : '{print $1}' /etc/passwd`; do INCLUDE+=\"/home/${Z}/.ssh/authorized_keys \"; done; echo $INCLUDE")

How can I correctly escape the above command to make it a valid request?

share|improve this question
up vote 1 down vote accepted

Using this statement you get some strange result like /home/bin, /home/root or /home/daemon.

for Z in `awk -F : '{print $1}' /etc/passwd`; do INCLUDE+="/home/${Z}/.ssh/authorized_keys "

ls /home/*/.ssh/authorized_keys fits better.

So the resulting script could be:

INCLUDE=$(ssh "ls /home/*/.ssh/authorized_keys")

But you need connect as a root to ssh-server

share|improve this answer
That is more elegant for sure, however this returns only my authorized_keys file. I've also tried with sudo and had the same result. – J0hnG4lt Jan 11 '13 at 13:13
Add the comment about root – dchirikov Jan 11 '13 at 13:19
While I wait for peer review, I've updated the above answer to work with sudo as enabling root ssh is probably not a good idea: INCLUDE=$(ssh "sudo su -c 'ls /home/*/.ssh/authorized_keys'") – J0hnG4lt Jan 11 '13 at 13:47
sgeorge-mn:~ sgeorge$ cat 
ssh -q suku@ <<'HERE'
cat /etc/passwd | grep '/bin/bash'| awk -F: '{system("ls /home/"$1"/.ssh/authorized_keys")}'

sgeorge-mn:~ sgeorge$ INCLUDE=$(bash
suku@'s password: 

sgeorge-mn:~ sgeorge$ echo $INCLUDE
/home/root/.ssh/authorized_keys /home/suku/.ssh/authorized_keys
share|improve this answer

The most error-prone method would be actually get each user's HOME dir from passwd database and check it for authorized_keys files. Also note that openssh supports both authorized_keys AND authorized_keys2 files.

This command should give such list:

getent passwd | awk -F: '$6!=""{print $6}' | \
    xargs -rI{} find {} -maxdepth 2 -mindepth 2 \
        -path \*/.ssh/\* \
        \( -name authorized_keys -o -name authorized_keys2 \) \
        -type f 2>/dev/null

You have to escape quotes appropriately if you're going to execute it via ssh. However, you can put it in script file and feed it to /bin/sh on the remote side:

<scriptfile ssh /bin/sh
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.