gpt4 book ai didi

linux - 为什么 tcpdump 不在后台运行?

转载 作者:行者123 更新时间:2023-12-04 16:17:06 26 4
gpt4 key购买 nike

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

#!/bin/bash
APP_NAME=`basename $0`
CFG_FILE=$1
. $CFG_FILE #just some variables
CMD=$2
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 在后台运行,将命令结果重定向到 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时,运行停止脚本后,它是空的。

发生了什么?我该如何解决?

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

作者似乎也遇到过类似的问题。他们争论比赛条件,但我没有完全理解。

最佳答案

我不确定通过让启动脚本本身继续运行来完成什么,但我认为这里有一种方法可以完成你想要做的事情,即 start tcpdump并让它通过 nohup 继续运行不受挂断的影响.出于说明的目的,我已经稍微简化了一些事情 - 您可以随意添加任何您认为合适的变量,例如 nohup.out 输出目录、TIMESTAMP 等。

脚本 #1:tcpdump_start.sh

#!/bin/shrm -f nohup.outnohup /usr/sbin/tcpdump -ni eth0 -s 65535 -w file_result.pcap &# Write tcpdump's PID to a fileecho $! > /var/run/tcpdump.pid

脚本 #2:tcpdump_stop.sh

#!/bin/shif [ -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.pidelse        echo tcpdump not running.fi

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

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

关于linux - 为什么 tcpdump 不在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61019058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com