-1

in my bash script , I used the following syntax in order to test the ssh connection test

IP=12.3.4.55
sshpass -p secret123 /usr/bin/ssh -n -o  ConnectTimeout=100 -o StrictHostKeyChecking=no -xaq -q root@$IP exit

[[ $? -eq 0 ]] && echo ssh test is ok || echo ssh test is fail

but I want to do it with a & ( so all ssh line will run ss process )

so I did this

IP=12.3.4.55
sshpass -p secret123 /usr/bin/ssh -n -o  ConnectTimeout=100 -o StrictHostKeyChecking=no -xaq -q root@$IP exit   &

[[ $? -eq 0 ]] && echo ssh test is ok || echo ssh test is fail

but the ssh test as the last above example works even IP address is wrong , so even ssh failed then $? get 0 inspite ssh test is failed

so how to set all ssh syntax with & ?

note - the reason that I want to add & on line is because we need to scan more then 1000 linux machines and with & it will be more faster

1
  • added more to the answer - might work for you / might not. Doesn't for me because I can't use sshpass, and so the ssh fails cause it can't attach to the TTY ..
    – Mr R
    Mar 17, 2021 at 10:14

2 Answers 2

4

Just move the test into a function so your script can run it in the background and test multiple connections in parallel:

#!/bin/bash

testConnection(){
  user=$1
  ip=$2
  sshpass -p secret123 /usr/bin/ssh -n -o  ConnectTimeout=100 -o StrictHostKeyChecking=no -xaq -q "$user"@"$ip" exit
  [[ $? = 0 ]] && echo "$user@$ip OK" || echo "$user@$ip FAILED"
}

users=( terdon terdon )
ips=( 123.4.5.6 127.1.0.0 )
for ((i=0;i<${#users[@]};i++)); do
   testConnection "${users[i]}" "${ips[i]}" &
done

## The script should wait and not exit until
## all background processes finish.
wait

You can then run it like this:

$ foo.sh
[email protected] FAILED
[email protected] OK
0
3

If you care about the result, then at some point you have to wait for the result when the command is run in background/sub-shell (learn more at TLDP https://tldp.org/LDP/abs/html/subshells.html).

In the sample what is checked is has the "create-a-subshell" part of it succeeded, not the "whats-running in the sub-shell".

You might also be able to do something like this - have a function that runs in the subshell instead ...

#!/bin/bash

testIp() {
        ip=$1
        user=$2
        sshpass ... ssh -n -o  ConnectTimeout=100 -o StrictHostKeyChecking=no -xaq -q $USER@$IP exit

        [[ $? = 0 ]] && echo ssh test is ok || echo ssh test is fail
}

( testIp YOURIP root ) &
( testIp YOUROTHERIP root2 ) &
1
  • Argh, sorry about the incomplete edit!
    – terdon
    Mar 17, 2021 at 11:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .