0

So I need to repeatedly try submitting a 4 digit number to a port on the local host, and then evaluate the response I get from the port if it contains a specific string, which I do with grep. I used something like echo {0000...9999} | nc localhost port. However, I cannot get this nice sequence expansion that I get from this command to work in a bash script. How could I go about writing a bash script for this problem?

  • 1
    what is the differences of 0001 with 1 as ports? – αғsнιη Mar 26 '18 at 8:15
3

You can use within a for-loop like following:

for i in {0001..9999}; do
    grep -q 'specificString' <<<"$(nc localhost $i)" && \
    echo "found on $i" || echo "not found on $i";
done
  • Thank you, that's exactly what I did and was about to report on it lol. – sarpu Mar 26 '18 at 8:25
1

For shells that does not support brace expansions, or that does not preserve zero padding:

i=0
while [ "$i" -le 9999 ]; do
    printf '%04d\n' "$i"
    i=$(( i + 1 ))
done | nc ...other options... | grep ...etc...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.