Havens
Havens

Reputation: 1

Nested If Statement with ssh

I am attempting to create a script that will A) cycle through a list of IP's and ping them, if successful attempt to log in using known credentials and if successful with that add the host to a list so the actions do not repeat.

This script runs as expected if A) the host is unavailable to ping or B) if it is available and my known credentials work. If it can ping the host but the ssh connection is rejected the script quits instead of using the next variable (or IP). Thanks!

What I have so far:

while read p; do
  ping -c1 -t1 $p
  if [ $? -eq 0 ]
  then
    /usr/local/bin/sshpass -p $PW ssh -o StrictHostKeyChecking=no "$USR"@"$p" </dev/null "
    scutil --get ComputerName" | tee -ai $WORKING

    MACHINE=$(head -n 1 $WORKING)

    if grep -Fxq $MACHINE "$FULL"
    then
      echo $MACHINE has been worked on already

    else
      echo $MACHINE has not been worked on
      echo $MACHINE >> $FULL
      rm -rf $WORKING
    fi

  else
    echo ping fail
  fi
done </iprange.txt

Upvotes: 0

Views: 335

Answers (1)

Nicola Worthington
Nicola Worthington

Reputation: 548

I'm not entirely sure what the question is, but it looks like your ssh command is probably eating your STDIN from your while read loop.

Either try changing which FD your read command is reading from:

while read -u 9 -r p ; do
  echo "$p"
done 9< /iprange.txt

Or try using the -n argument to your ssh command which redirects STDIN from /dev/null (prevents reading of your STDIN from /iprange.txt).

Upvotes: 1

Related Questions