shell脚本--筛选出合法ip地址

shell脚本–筛选出合法ip地址

作者:蓝眼泪

实验环境:centos7.9,vm15.
路径 :/root
临时文件有:ip_test1.txt 和 ip_test2.txt.
最终保存的合法ip文件:ip_test.txt

第一步 创建样本文件ip.txt

内容如下:

192.168.1.103
192.168.1.300
0.0.0.0
1.1.1.1
300.1.1.1
1.300.1.1
1.1.300.1

第二步 用普通for循环创建脚本

脚本名称是ipdetect.sh
内容如下:

#!/bin/bash

grep "^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$" /root/ip.txt >/root/ip_test1.txt

line=$(wc -l /root/ip_test1.txt |awk '{print $1}')
echo "" > /root/ip_test.txt
for (( i=1;i<=$line;i=i+1 ))
do 
   cat /root/ip_test1.txt |awk ' NR=='$i' {print} ' >/root/ip_test2.txt
   a=$( cat /root/ip_test2.txt |cut -d "." -f 1 )
   b=$( cat /root/ip_test2.txt |cut -d "." -f 2 ) 
   c=$( cat /root/ip_test2.txt |cut -d "." -f 3 )
   d=$( cat /root/ip_test2.txt |cut -d "." -f 4 )
   if [ "$a" -lt 1 -o "$a" -gt 255 ]
       then
    		continue 
   fi

   if [ "$b" -lt 0 -o "$b" -gt 255 ]
     then
   	 	continue 
   fi

   if [ "$c" -lt 0 -o "$c" -gt 255 ]
	then
        	continue
   fi
 
   if [ "$d" -lt 0 -o "$d" -gt 255 ]
	then
	   	continue
   fi
  
   cat /root/ip_test2.txt >> /root/ip_test.txt

done
rm -rf /root/ip_test1.txt
rm -rf /root/ip_test2.txt

第三步 使用for in 方法创建脚本

脚本名称为ipdetect001.sh

#!/bin/bash

grep "^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$" /root/ip.txt > /root/ip_test1.txt
echo "" > /root/ip_test.txt

for i in $(cat /root/ip_test1.txt)
do
        a=$(echo $i | cut -d '.' -f 1)
        b=$(echo $i | cut -d '.' -f 2)
        c=$(echo $i | cut -d '.' -f 3)
        d=$(echo $i | cut -d '.' -f 4)

        if [ "$a" -lt 1 -o "$a" -gt 255 ]
                then
                        continue
        fi

        if [ "$b" -lt 0 -o "$b" -gt 255 ]
                then
                        continue
        fi    

        if [ "$c" -lt 0 -o "$c" -gt 255 ]
                then
                        continue
        fi
        if [ "$d" -lt 0 -o "$d" -gt 255 ]
                then
                        continue
        fi

        echo "$i" >> /root/ip_test.txt
done
rm -rf /root/ip_test1.txt
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值