bash 循环内的管道与循环后的管道

bash pipe inside loop vs piping after loop

我正在做一些在线挑战。 lvl 要求我们进行一些暴力破解。

现在这两种解决方案有什么区别:

## Solution 1
for i in $(seq -w 9999); do 
  echo "password_previous_lvl $i" 
done | nc localhost 30002

## Solution 2
for i in $(seq -w 9999); do 
  echo "password_previous_lvl $i" | nc localhost 30002
done

此处唯一发生变化的是管道。

我尝试只执行 shell 中的命令。输出是:

bandit24@bandit:~$ echo "password_previous_lvl 2525" | nc localhost 30002
I am the pincode checker for user bandit25. Please enter the password for user bandit24 and the secret pincode on a single line, separated by a space.
Wrong! Please enter the correct pincode. Try again.

Timeout. Exiting.

超时。

如果我直接在 shell 中使用其他密码重试,输出为:

bandit24@bandit:~$ echo "password_previous_lvl 2525" | nc localhost 30002
I am the pincode checker for user bandit25. Please enter the password for user bandit24 and the secret pincode on a single line, separated by a space.
Wrong! Please enter the correct pincode. Try again.
password_previous_lvl 2526
Timeout. Exiting.

只是在结束时超时,就像之前一样,没有错误消息。

所以我不明白为什么当我在循环末尾使用带有管道的解决方案 1 时,我正确地得到了这个结果:

bandit24@bandit:/tmp$ ./b.sh
I am the pincode checker for user bandit25. Please enter the password for user bandit24 and the secret pincode on a single line, separated by a space.
Wrong! Please enter the correct pincode. Try again.
Wrong! Please enter the correct pincode. Try again.
......
Wrong! Please enter the correct pincode. Try again.
Correct!
The password of user bandit25 is XXXXXXXXXXXXXXX

Exiting.

有人可以解释一下原因吗?

还有一个问题:为什么找到好的pin就结束了,不继续了?

非常感谢您的帮助。

感谢@Raman Sailopal 的评论

In the first solution you are opening the connection only once and sending the echo statement 9999 times. In the second, you set up the connection 9999 times and then send the echo statement once for each connection.