在 bash 脚本中运行 tcpdump

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22369466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:53:36  来源:igfitidea点击:

Running tcpdump inside bash script

bash

提问by user238021

I am trying to get some numbers from tcpdump inside a shell script and print that number.

我试图从 shell 脚本中的 tcpdump 获取一些数字并打印该数字。

Here is my script

这是我的脚本

while true
do
{
 b=`tcpdump -n -i eth1 | awk -F'[, ]' '{print }'`
echo $b
}
done

When I execute this script, I get this

当我执行这个脚本时,我得到了这个

tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth1, link-type EN10MB (Ethernet), capture size 65535 bytes

Is there anything special I need to do to capture tcpdump o/p inside shell script ?

我需要做什么特别的事情来捕获 shell 脚本中的 tcpdump o/p 吗?

回答by Gordon Davisson

By default, tcpdumpruns forever (or until it's interrupted by Control-C or something similar). The

默认情况下,tcpdump永远运行(或直到它被 Control-C 或类似的东西中断)。这

b=`tcpdump ...`

construct runs until tcpdumpexits... which is never ... and thenputs its output into $b. If you want to capture the output from a single packet, you can use tcpdump -c1 ...(or -c5to capture groups of 5, or similar). Alternately, you could let it run forever but capture its output one line at a time with a while readloop (although you need to use tcpdump -lto prevent excessive buffering):

构造运行直到tcpdump退出...永远不会...然后将其输出放入$ b。如果要捕获单个数据包的输出,可以使用tcpdump -c1 ...(或-c5捕获 5 个或类似的组)。或者,您可以让它永远运行,但使用while read循环一次捕获一行输出(尽管您需要使用它tcpdump -l来防止过度缓冲):

tcpdump -l -n -i eth1 | awk -F'[, ]' '{print }' | while read b; do
    echo $b
done

I'm not entirely sure what your script is supposed to do, but I see some other issues. First, unless your version of tcpdumpis much more consistent than mine, printing the 10th comma-delimited field of each packet will notget you anything meaningful. Here's some sample output from my computer:

我不完全确定您的脚本应该做什么,但我看到了一些其他问题。首先,除非您的版本tcpdump比我的更一致,否则打印每个数据包的第 10 个逗号分隔字段不会让您获得任何有意义的信息。这是我的计算机的一些示例输出:

00:05:02:ac:54:1e
1282820004:1282820094
90
73487384:73487474
1187212630:1187212720
90
90
host


2120673524

Second, what's the point of capturing the output into a variable, then printing it? Why not just run the command and let it output directly? Finally, echo $bmay garble the output due to word splitting and wildcard expansion (for example, if $b happened to be "*", it would print a list of files in the current directory). For this reason, you should double-quote variables when you use them (in this case, echo "$b").

其次,将输出捕获到变量中然后打印它有什么意义?为什么不直接运行命令,让它直接输出呢?最后,echo $b可能由于分词和通配符扩展导致输出乱码(例如,如果 $b 恰好是“*”,它会打印当前目录中的文件列表)。出于这个原因,您应该在使用变量时用双引号引用它们(在本例中为echo "$b")。