I HATE YOU, OPENSSH!
2015 January 13Sometimes, but just sometimes, I really, really hate OpenSSH. Consider the following code:
#!/bin/bash
while read hostname; do
ssh -o PasswordAuthentication=no -i secret.key "${hostname}" \
"echo \$(hostname): \$(date -u)"
done < listofhosts.txt
The file listofhosts.txt contains - surprise - a list of hostnames, one per line. The expected output of this small script is something like this:
flora: Tue Jan 13 09:39:18 UTC 2015
pallas: Tue Jan 13 09:39:19 UTC 2015
athene: Tue Jan 13 09:39:21 UTC 2015
lutetia: Tue Jan 13 09:39:22 UTC 2015
Simple enough as far as scripts go, right? WRONG!
Now, what you DO get is this:
flora: Tue Jan 13 09:40:07 UTC 2015
Why? Because OpenSSHs ssh command drains STDIN. Why? No idea! Because it can, I guess. To get the above expected output, you need to do this:
#!/bin/bash
exec 3<listofhosts.txt
while read hostname <&3; do
ssh -o PasswordAuthentication=no -i secret.key "${hostname}" \
"echo \$(hostname): \$(date -u)"
done
Hope that helps you somewhere down the line.
EOF
Category: blog
Tags: openssh rant shellscripting