Search code examples
linuxbashcentos

My while read command isn't opening a while loop


I'm trying to use the while read command to create a comma separated table of names, routers, and IP addresses. It should then SSH through that series of routers with the router1 value, input a command, and extract the IP addresses it should return, then write them to a file. It is my understanding that I can do this with read.


 grep -v '^#' /opt/pp1/projectprefixed/peeringinfo > /opt/pp1/projectprefixed/$DATE/peeringinfo.conf

ip_regex='([0-9]{1,3}\.){3}[0-9]{1,3}'

while IFS=, read NREN router1 peering
do

  if [ ! -f /opt/pp1/projectprefixed/$DATE/recFromNRENList/$router1 ] 
    then
    ssh -q -n -o StrictHostKeyChecking=no srv_oc_scripts@$router1 "show route recieve-protocol bgp" | grep -o "$ip_regex" > peeringsReceived
  fi

done < $router1

The table is a text like that looks like this:

NAME1,mx1.ROUTER1,192.168.1.1
NAME2,mx1.ROUTER2,192.168.65.7

However, it returns an "ambiguous redirect" error.


Solution

  • There are several major logic errors

    1. ssh will consume stdin. Read from a different file descriptor
      while IFS= read -r NREN router1 peering <&3; do
        ...
      done 3< 4router1
      
    2. router1 appears to be initialized in the read command, but is used as an input file to the loop beforehand, and as the ssh remote host, and as a file name you test for existence, and as the output file for the loop commands. I can't tell how this file is supposed to exist, and what contents it's supposed to have
    3. grep will also consume stdin: You probably forgot to specify what input you want for grep

    I want to ssh into a router, run the specified command and pull only the matching pattern and write it to a file. It's meant to be an IP address

    As a wile stab in the dark, perhaps you want

    ip_regex='([0-9]{1,3}\.){3}[0-9]{1,3}'
    output_dir="/opt/pp1/projectprefixed/$DATE/recFromNRENList"
    router1=???
    
    ip_addr=$(
        ssh -q -n -o StrictHostKeyChecking=no \
            "srv_oc_scripts@$router1" \
            "show route recieve-protocol bgp" \
        | grep -o "$ip_regex"
    )