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