【发布时间】: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