You are not logged in.

#1 2016-06-20 23:42:02

whiskeytango3000
Member
Registered: 2016-06-19
Posts: 5

[SOLVED] Pass arrays to ssh in Bash

*** Solved by Trilby in the second post ***

In a bash function I want to retrieve stats from multiple machines via sshpass and ssh. The following gives the error, "ssh: Could not resolve hostname ]}: Name or service not known"

#!/bin/bash
declare -a hostlist=("25.86.98.106" "25.90.122.149" "25.17.23.135" "25.132.240.211" "...cont...")
get_stats() {
for each in "{$hostlist[@]}"
  do
    sshpass -p Password ssh -p 2222 -o StrictHostKeyChecking=no -o ConnectTimeout=10 user@"{$each[@]}" -n "cat /etc/hostname && uptime | awk '{print \$3}'" >> uptimes.txt
done
}
get_stats

Substituting * for @ in both $hostlist and $each yields the error

ssh: Could not resolve hostname {{25.86.98.106[*]}[*]}: Name or service not known

Remove "sshpass -p Password" and the function works, but only for the first IP in the hostlist array. Is this due to trying to expand the variable $each in an ssh subshell of sshpass? Sorry, the vernacular is new to me so I might call a thing by the wrong name. wink I'd like to understand what's causing this behavior, and how to make this work if possible. Unfortunately I do not have the option of using ssh-keygen, ssh-copy-id...

Links to your favorite resources on these topics are most welcome! Thanks.

Last edited by whiskeytango3000 (2016-06-21 00:17:42)

Offline

#2 2016-06-20 23:45:50

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,452
Website

Re: [SOLVED] Pass arrays to ssh in Bash

{$array[@]} != ${array[@]}

and "each" is not an array in the loop, so

{$each[@]} != $each

http://mywiki.wooledge.org/BashGuide

EDIT: Also, while it is not actually an error, I'd argue that "each" is a horrible name for a variable in this context.  It doesn't represent "each" it represents a single ip/server - and more importantly 'foreach' and 'for each' are common language keywords in other programming/scripting languages and are thus easily misleading here.  'for server in ...' would be much more clear.


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#3 2016-06-21 00:15:43

whiskeytango3000
Member
Registered: 2016-06-19
Posts: 5

Re: [SOLVED] Pass arrays to ssh in Bash

Aha! So I was telling ssh to connect to a non-existent array, while referring incorrectly to the real array in the first place, thanks to a misplaced $. Checking out Greg's Bash guide now. Thanks for the help and advice, Trilby.

EDIT: Offtopic, but I had to say thanks again. That Bash guide (new version at http://guide.bash.academy) is exactly what I needed!

Last edited by whiskeytango3000 (2016-06-22 04:09:03)

Offline

Board footer

Powered by FluxBB