This article mainly introduces the script for Verifying IP address legality implemented by python and shell. each script is executed. if you need it, refer
I. check IP address validity in python
Execution result:
Python code:
The code is 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 ('.') # cut the IP address into a list
# Print addr
If len (addr )! = 4: # the list after cutting must have four parameters
Print "check ip address failed! "
Sys. exit ()
For I in range (4 ):
Try:
Addr [I] = int (addr [I]) # each parameter must be a number; otherwise, verification fails.
Except t:
Print "check ip address failed! "
Sys. exit ()
If addr [I] <= 255 and addr [I]> = 0: # each parameter value must be between 0 and.
Pass
Else:
Print "check ip address failed! "
Sys. exit ()
I + = 1
Else:
Print "check ip address success! "
If len (sys. argv )! = 2: # the input length must be 2
Print "Example: % s 10.0.0.1" % sys. argv [0]
Sys. exit ()
Else:
Check_ip (sys. argv [1]) # The IP address verification function is called to meet the condition.
2. verify the validity of IP addresses using shell
Execution result:
The value 0 is valid, and the value 0 is invalid.
Shell code:
The code is 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;
# The IP address must be a full number.
If [$? -Ne 0]
Then
Return 1
Fi
Ipaddr = $1
A = 'echo $ ipaddr | awk-F. '{print $1}' # separated by "." to retrieve the values of each column
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] # each value must be between 0 and.
Then
Return 1
Fi
Done
Return 0
}
If [$ #-ne 1]; then # determine the parameter quantity
Echo "Usage: $0 ipaddress ."
Exit
Else
CheckIPAddr $1
Fi