The Python and Shell implementations of the verification IP address legality scripting sharing _python

Source: Internet
Author: User

One, Python verify IP address legality

Execution effect:

Python code:

Copy Code code as follows:

[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]) #每个参数必须为数字, or the checksum fails
Except
print "Check IP address failed!"
Sys.exit ()
If addr[i]<=255 and addr[i]>=0: between #每个参数值必须在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函数

Second, the shell verify the legality of IP address

Implementation of the School fruit:
The return value of 0 is verified to be valid, not 0 illegal.

Shell code:

Copy Code code as follows:

[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 '} ' #以. ' Separate, remove the value of each column
B= ' echo $ipaddr |awk-f. ' {print $} '
C= ' echo $ipaddr |awk-f. ' {print $} '
D= ' echo $ipaddr |awk-f. ' {print $} '
For num in $a $b $c $d
Todo
If [$num-gt 255] | | [$num-lt 0] #每个数值必须在0-255
Then
Return 1
Fi
Done
return 0
}
If [$#-ne 1];then #判断传参数量
echo "Usage: $ ipaddress."
Exit
Else
CHECKIPADDR $
Fi

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.