【问题标题】:bash script to log/print all connections in the last N seconds用于记录/打印最后 N 秒内所有连接的 bash 脚本
【发布时间】:2015-06-02 07:59:15
【问题描述】:

我想:在后台运行一个脚本,每 X 秒打印一次,例如:

tcp        0      0 localhost:5555          localhost:47824         ESTABLISHED
tcp        0      0 localhost:47824         localhost:5555          ESTABLISHED

即使连接已经关闭,所以我会看到在那个时间跨度内打开了哪些连接(无论是关闭还是打开都无关紧要)。

我这样做是为了将输出尾随到一个临时文件:

#!/bin/sh


    #dump netstat result of established connections to a temp file
    (netstat -c | grep --line-buffered ESTABLISHED >> 1.tmp &)


while true
do
    #copy the file with the dump and flush it, something like log rotation
    #THE PROBLEM IS HERE######
    cp 1.tmp 2.tmp && rm 1.tmp
    ##########################

    #add a prefix on each line to reconize the logs
    sed -i -e 's/^/Connections: /' 2.tmp

    #print the logs to standard output, only one entry for each connection
    cat 2.tmp | uniq


    sleep 10
done

显然这不是正确的方法,因为删除文件会杀死 netstat 进程,我认为它只会创建另一个新文件。

我可以使用 netstat 上的 head 命令来阻止它每 X 行并更改文件,但我不确定这是否会导致在非常快速的连接/断开时丢失一些信息

欢迎使用任何其他可靠的方式记录连接,请记住,我没有 root 权限,但我只需要知道也运行此脚本的用户建立的连接,所以很好。

编辑:我对我刚刚发布的实际解决方案不满意,因为默认情况下 netstat 每秒运行一次,并且某些连接可能更快,我需要一种方法来获取运行此程序的用户建立的所有出站连接脚本(记住,没有 root 权限)。目前我正在尝试netstat -c 0.1,但我仍然无法信任它

【问题讨论】:

  • 你可以只删除 1.tmp 的内容。我会这样做 cat 1.tmp > 2.tmp && > 1.tmp ,它将 1.tmp 的内容重定向到 2.tmp ,如果成功,它将删除 1.tmp 的内容

标签: bash file networking grep netstat


【解决方案1】:

这是包含@vlp 建议的工作脚本以及获得独特结果的修复,因为只有uniq 还不够,我需要对它们进行排序以获得独特的行。

#!/bin/sh


    #dump netstat result of established connections to a temp file
    (netstat -c | grep --line-buffered ESTABLISHED >> 1.tmp &)


while true
do
    #redirect content of 1.tmp to 2.tmp and remove it from 1.tmp
    cat 1.tmp > 2.tmp && > 1.tmp


    #add a prefix on each line to reconize the logs
    sed -i -e 's/^/Connections: /' 2.tmp

    #print the logs to standard output, only one entry for each connection
    cat 2.tmp | sort -u

    #delete the file
    rm 2.tmp

    sleep 10
done

【讨论】:

    【解决方案2】:

    作为一种替代方法,您可能需要考虑调查是否可以插入iptables 规则来记录连接建立,并让您的脚本解析生成的日志。这可能需要更多的工作,但应该报告短暂的连接,并且可以(如果需要)记录被拒绝的连接等等。

    【讨论】:

    • 是的,对于更详细的信息,这将是一个更好的解决方案,但如果没有 root 权限是不可能的(我没有权限,不仅用于实际的日志记录脚本)
    猜你喜欢
    • 2012-12-15
    • 2016-01-15
    • 2015-04-30
    • 2014-04-29
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    相关资源
    最近更新 更多