我有一个 1 行程序,它将把 telnet 会话的输出写入文件。
while sleep 5; do sleep 1 | telnet 11.22.33.44 443 | tee -a /var/tmp/test$(date +%Y%m%d).txt && date >> /var/tmp/test$(date +%Y%m%d).txt; done &
我不想看到第一个命令的输出,但是我想运行这 1 个命令并显示输出:
awk '!/Trying/{count++}/Trying/{if (count == 4) print "Connected"; else if (count == !NR) print ""; else print "Failed"; count = 0}' test$(date +%Y%m%d).txt
额外奖励是!可以将两者放在一行中,显示如下输出:
while sleep 5; do sleep 1 | telnet 159.203.162.223 443 | tee -a /var/tmp/test$(date +%Y%m%d).txt && date >> /var/tmp/test$(date +%Y%m%d).txt; done & awk '!/Trying/{count++}/Trying/{if (count == 4) print "Connected"; else if (count == !NR) print ""; else print "Failed"; count = 0}' test$(date +%Y%m%d).txt
Connected
Connected
Connected
Connected
Connected
Connected
Connected
Connected
Connected
Connected
答案1
如果可能的话,您可能要考虑使用netcat
( nc
),而不是尝试解析telnet
输出。例如:
$ while sleep 5; do nc -C 93.184.216.34 443 </dev/null && echo "Connected" | tee -a /var/tmp/test$(date +%Y%m%d).txt && date >> /var/tmp/test$(date +%Y%m%d).txt; done
Connected
Connected
Connected
Connected
^C
--
$ cat /var/tmp/test20180925.txt
Connected
Tue Sep 25 16:42:57 UTC 2018
Connected
Tue Sep 25 16:43:02 UTC 2018
Connected
Tue Sep 25 16:43:07 UTC 2018
Connected
Tue Sep 25 16:43:12 UTC 2018
尝试一下更接近你正在寻找的内容
while sleep 5; do sleep 1 | nc -v 159.203.162.223 443 2>&1; echo $(date) >> /var/tmp/test$(date +%Y%m%d).txt; done >> /var/tmp/test$(date +%Y%m%d).txt & tail -f /var/tmp/test$(date +%Y%m%d).txt | grep 'Connected\|timed\|refused'