python和shell实现的校验IP地址合法性脚本分享

WBOY
Release: 2016-06-10 15:19:26
Original
1169 people have browsed it

一、python校验IP地址合法性

执行效果:

python代码:

复制代码 代码如下:
 
[root@yang python]# vi check_ip.py
#!/usr/bin/python
import os,sys
def check_ip(ipaddr):
        import sys
        addr=ipaddr.strip().split('.')   #切割IP地址为一个列表
        #print addr
        if len(addr) != 4:   #切割后列表必须有4个参数
                print "check ip address failed!"
                sys.exit()
        for i in range(4):
                try:
                        addr[i]=int(addr[i])   #每个参数必须为数字,否则校验失败
                except:
                        print "check ip address failed!"
                        sys.exit()
                if addr[i]=0:    #每个参数值必须在0-255之间
                        pass
                else:
                        print "check ip address failed!"
                        sys.exit()
                i+=1
        else:
                print "check ip address success!"
if  len(sys.argv)!=2:  #传参加本身长度必须为2
        print "Example: %s 10.0.0.1 "%sys.argv[0]
        sys.exit()
else:
        check_ip(sys.argv[1])   #满足条件调用校验IP函数

二、shell校验IP地址合法性

执行校果:
  返回值0校验合法,非0不合法。

shell代码:

复制代码 代码如下:

[root@yang python]# vi check_ip.sh
#!/usr/bin/sh
CheckIPAddr()
{
echo $1|grep "^[0-9]\{1,3\}\.\([0-9]\{1,3\}\.\)\{2\}[0-9]\{1,3\}$" > /dev/null;
#IP地址必须为全数字
        if [ $? -ne 0 ]
        then
                return 1
        fi
        ipaddr=$1
        a=`echo $ipaddr|awk -F . '{print $1}'`   #以"."分隔,取出每个列的值
        b=`echo $ipaddr|awk -F . '{print $2}'`
        c=`echo $ipaddr|awk -F . '{print $3}'`
        d=`echo $ipaddr|awk -F . '{print $4}'`
        for num in $a $b $c $d
        do
                if [ $num -gt 255 ] || [ $num -lt 0 ]     #每个数值必须在0-255之间
                then
                        return 1
                fi
        done
                return 0
}
if [ $# -ne 1 ];then            #判断传参数量
        echo "Usage: $0 ipaddress."
        exit
else
CheckIPAddr $1
fi
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!