Shell通过多线程对文件进行IP统计

#!/bin/bash

##统计IDS ftp目录下当天多个json文件中的所有IP,并进行排序,最终结果存放在${result_file}
#采用多线程

grep_result="/tmp/grep.txt"
result_file="/tmp/result.txt"
#提取最新flow文件数据
ftp_path=$(find /twas-nds/ftp_root/result-data/flow-files/ -type d|tail -n 1)
result_json="/tmp/result"
set -x

check_status(){
###检测程序是否运行,避免程序重复启动
ps -ef|grep $0|grep -v $$|grep -v grep&&exit
}

delete_tmp_file(){
#删除上次残留数据
[ -d $result_json ]||mkdir -p $result_json
[ -f $grep_result ]&&rm -rf $grep_result
[ -f $result_file ]&&rm -rf $result_file
}

search_data(){
thread_num=400       ##调整线程数
tempfifo="my_temp_fifo"

mkfifo ${tempfifo}
exec 6<>${tempfifo}
rm -f ${tempfifo}


for ((i=1;i<=${thread_num};i++))
do
{
	echo;
}

done >&6

#获取最新flow文件
for file in $(find $ftp_path -type f|grep json);do
	read -u6
	{
	###考虑到多线程同时写一个文件会造成文件内容出现写入的ip格式错误问题
        ###因此将每个文件匹配到的IP分别写入对应的json文件中
		touch ${result_json}/${file##*/}
		for json in $file;do
			#提取flow文件中匹配到的IP,存入对应的json文件中
                	grep -oE '((([0-9]+)\.){3}([0-9]+))' $json|grep -v $HOSTNAME|sort|uniq >>${result_json}/${file##*/}
		done

		echo " ">&6
	}&
done
wait
exec 6>&-
}

total_data(){
	cd $result_json
	#将所有json文件中的ip去重,汇总到一个文件
	ls|grep json|xargs -i -t cat {}|awk '!a[$0]++' >>$grep_result
}

result_data(){
	#汇总文件中匹配到的ip根据顺序进行排序
	grep -oE '((([0-9]+)\.){3}([0-9]+))'  $grep_result|sort -t"." -k1,1n -k2,2n -k3,3n -k4,4n|uniq >>${result_file}
	[ -f $grep_result ]&&rm -rf $grep_result
	[ -d $result_json ]&&rm -rf $result_json
}

Main(){
	check_status
	delete_tmp_file
	search_data
	total_data
	result_data
}


Main

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值