【问题标题】:Why doesn't tcpdump run in background?为什么 tcpdump 不在后台运行?
【发布时间】:2020-04-03 19:22:55
【问题描述】:

我通过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

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

【问题讨论】:

  • 不,它没有。但它应该可以工作,传递的命令不会改变任何东西。
  • 脚本是用'&'字符调用的,我忘了。我会更新问题。

标签: linux shell tcpdump nohup


【解决方案1】:

我不确定您要通过让启动脚本本身继续运行来完成什么,但我认为这是一种可以完成您正在尝试做的事情的方法,即启动 tcpdump 并让它继续通过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 & # 将 tcpdump 的 PID 写入文件 回声$! > /var/run/tcpdump.pid

脚本 #2:tcpdump_stop.sh

#!/bin/sh 如果 [ -f /var/run/tcpdump.pid ] 然后 杀死`cat /var/run/tcpdump.pid` echo tcpdump `cat /var/run/tcpdump.pid` 被杀死。 rm -f /var/run/tcpdump.pid 别的 echo tcpdump 未运行。 菲

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

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

【讨论】:

  • 你好克里斯托弗。确实,您的解决方案有效。但是,我不明白为什么我的没有。我做了一些测试,用我的方法,当脚本完成时,tcpdump 进程被终止,甚至用'nohup'和'&'字符调用脚本。感谢您的帮助。
【解决方案2】:

在 SSH 会话上运行 tcpdump 时,我也遇到了问题。 就我而言,我正在跑步

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

问题在于,在 Paramiko SSH 会话中作为后台进程运行此命令。

为了解决这个问题,我使用了 Linux 的 screen 实用程序。 screen 是一个易于使用的工具,可将流程作为服务长时间运行。

【讨论】:

    猜你喜欢
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多