python和shell实现的校验IP地址合法性脚本分享,pythonshell
python和shell实现的校验IP地址合法性脚本分享,pythonshell
一、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]<=255 and 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
你试着用while循环来读看看,从你的代码我只看到一次读嘛。。
举例:shell的脚本:t.sh内容:echo "this is a test shell with arguments"echo "arg1 = $1; arg2 = $2;"执行脚本./t.sh zhao结果如下:[noncode@gnode108 knockdown_workflow]$ ./t.sh zhao1 zhao2this is a test shell with argumentsarg1 = zhao1; arg2 = zhao2;python脚本:[noncode@gnode108 knockdown_workflow]$ cat t.py #!/usr/bin/env pythonimport osimport sysdef main():print 'Hello world!'if len(sys.argv) < 2 : print "usage:%s config log" %(sys.argv[0]) sys.exit(1)arg0 = sys.argv[0]arg1 = sys.argv[1]print "arg0 = %s; arg1 = %s" % (arg0, arg1) print "test ./t.sh: "os.system('./t.sh ' + arg0 + ' ' + arg1)print "test method of replacing: "t = 't.sh'm = 'zhao'n = 'zhao'cmd = "./%s %s %s" % (t,m,n)print "t = %s; m = %s; n = %s; cmd = %s" % (t,m,n,cmd)os.system(cmd)if __name__ == '__main__':main()运行脚本:python t.py t.sh执行结果:[noncode@gnode108 knockdown_workflow]$ python t.py t.shHello world!arg0 = t.py; arg1 = t.shtest ./t.sh: this is a test shell with argumentsarg1 = t.py; arg2 = t.sh;test method of replacing: t = t.sh; m = zhao; n = zhao; cmd = ./t.sh zhao zhaothis is a test shell with argumentsarg1 = zhao; arg2 = zhao;[noncode@gnode108 knockdown_workflow]$ cat t.sh echo "this is a test shell with arguments"echo "arg1 = $1; arg2 = $2;"[noncode@gnode108 knockdown_workflow]$ ./t.sh zhao1 zhao2this is a test shell with ar......余下全文>>
评论关闭