BASH:while循环和读取输出

时间:2014-07-21 15:20:16

标签: bash while-loop

我想在tcpdump取证工具列出的端口上运行unhide-tcp但是目前我无法通过if语句验证是否找到任何端口,因为{{ 1}}循环列出一行上的所有端口:while

1025 1026输出:

unhide-tcp

脚本:

# unhide-tcp 
Unhide-tcp 20130526
Copyright © 2013 Yago Jesus & Patrick Gouin
License GPLv3+ : GNU GPL version 3 or later
http://www.unhide-forensics.info
Used options: 
[*]Starting TCP checking

Found Hidden port that not appears in ss: 1025

Found Hidden port that not appears in ss: 1026
[*]Starting UDP checking

输出:

#!/usr/bin/env bash

set -f

DIR="/tmp"

while read PORT; do

# Debug msg
echo "Found Hidden port(s): ${PORT}"

    if [ ! -z ${PORT} ]; then

        echo "Found Hidden port(s): ${PORT}"
        timeout 10 tcpdump -c 50 port ${PORT} -w "${DIR}/$(date "+%Y%m%d-%T")-[${PORT}].pcap"
    fi

done <<<$(unhide-tcp | awk -F ":" '/^Found/{ print $2 }')

exit 0

2 个答案:

答案 0 :(得分:1)

您可以通过更改以下内容来解决此问题:

[ ! -x ${PORT} ]

为:

[ ! -x "$PORT" ]

将变量$PORT包装在引号中意味着变量的全部内容将被解释为单个参数。如果没有引号,如果变量包含空格,则每个“单词”将被解释为单独的参数。

答案 1 :(得分:1)

当您使用$(命令替换打开新shell时,所有换行符都将更改为空格。您可以将此命令的输出传递给while循环。

unhide-tcp | awk -F ":" '/^Found/{ print $2 }' | while read PORT; do
....
...

done