为什么 tcpdump 运行 不在后台?

Why doesn't tcpdump run in background?

我通过 ssh 登录了一个虚拟机,我试图在后台 运行 一个脚本,脚本如下所示:

#!/bin/bash
APP_NAME=`basename [=11=]`
CFG_FILE=
. $CFG_FILE #just some variables
CMD=
PID_FILE="$PIDS_DIR/$APP_NAME.pid"
CUR_LOG_DIR=$LOGS_RUNNING

echo $$ > $PID_FILE

#Main script code

#This script shall be called using the following syntax
# $ nohup script_name output_dir &

TIMESTAMP=`date +"%Y%m%d%H%M%S"`

CAP_INTERFACE="eth0"

/usr/sbin/tcpdump -nei $CAP_INTERFACE -s 65535 -w file_result

rm $PID_FILE

结果应该是 tcpdump 运行ning 在后台,将命令结果重定向到 file_result。

脚本调用方式:

nohup $SCRIPT_NAME $CFG_FILE start &

并且停止调用 STOP_SCRIPT:

##STOP_SCRIPT
PID_FILE="$PIDS_DIR/$APP_NAME.pid"

if [ -f $PID_FILE ]
then
  PID=`cat $PID_FILE`

  # send SIGTERM to kill all children of $PID
  pkill -TERM -P $PID
fi

当我检查 file_result 时,在 运行 停止脚本之后,它是空的。

这是怎么回事?我该如何解决?

我找到这个 link:https://it.toolbox.com/question/launching-tcpdump-processes-in-background-using-ssh-060614

作者好像遇到过类似的问题。他们争论竞争条件,但我完全没有理解。

我不确定您通过让启动脚本本身继续 运行 来尝试完成什么,但我认为这是一种可以完成您尝试做的事情的方法,即开始 tcpdump and have it continue to run immune to hangups via nohup。出于说明目的,我对事情进行了一些简化 - 请随意添加您认为合适的任何变量,例如 nohup.out 输出目录、TIMESTAMP

脚本 #1:tcpdump_start.sh

#!/bin/sh
rm -f nohup.out
nohup /usr/sbin/tcpdump -ni eth0 -s 65535 -w file_result.pcap &

# Write tcpdump's PID to a file
echo $! > /var/run/tcpdump.pid

脚本 #2:tcpdump_stop.sh

#!/bin/sh
if [ -f /var/run/tcpdump.pid ]
then
        kill `cat /var/run/tcpdump.pid`
        echo tcpdump `cat /var/run/tcpdump.pid` killed.
        rm -f /var/run/tcpdump.pid
else
        echo tcpdump not running.
fi

要启动 tcpdump,只需 运行 tcpdump_start.sh.
要停止以 tcpdump_start.sh 启动的 tcpdump 实例,只需 运行 tcpdump_stop.sh.

捕获的数据包将被写入file_result.pcap文件,是的,它是一个pcap文件,而不是文本文件,所以它有助于命名它正确的文件扩展名。当 tcpdump 终止时,tcpdump 统计信息将被写入 nohup.out 文件。

当 运行 通过 SSH 会话进行 tcpdump 时,我也遇到过问题。 就我而言,我是 运行

sudo nohup tcpdump -w {pcap_dump_file} {filter} > /dev/null 2>&1 &

其中,运行 这个通过 Paramiko SSH 会话作为 后台进程 的命令是问题所在。

为了解决这个问题,我使用了 Linux 的 screen 实用程序。 screen 是一个易于使用的工具,用于 long-running 进程即服务。