First, function description
Sometimes the project needs to pass the IP address to determine whether to allow access, usually through a white list address file to hold these allowed to release the IP, but each time the file editing is cumbersome to open, error-prone, do not know whether to add, so with Python wrote a script to automatically add white list.
Ii. contents of the script
#!/usr/bin/env python#coding:utf-8#2017-06-09 ver:1.0import syswhite_list= "White_list.txt" add_ Ip=sys.argv[1].strip () checkip=add_ip.split ('. ') If len (Checkip)!= 4: print ("ip[length") is illegal. Program Exit! ") sys.exit (5) Elif not checkip[0].isdigit () or not checkip[1].isdigit ( ) or not checkip[2].isdigit () or not checkip[3].isdigit (): print ("ip[is not a number") is illegal. Program Exit! ") sys.exit (5) Elif int (checkip[0]) >= 254 or int (checkIp[1]) > 255 or int (checkip[2]) >255 or int (checkip[3]) >255: print ("ip[Digital Range") is illegal. Program Exit! ") sys.exit (5) new_ip = str (add_ip + "\ n") F=open (white_list, ' R ') IPS=f.readlines () if new_ip in ips: print "the add ip %s is in White list. " % new_ip.split () Else: fw=open (wHite_list, ' A + ') fw.write (new_ip) print "the add ip %s add in white list ok~ " % new_ip.split () fw.close ()
III. Results of implementation
$./add_white.py 192.168.1.256
ip[number Range] illegal. Program Exit!
$./add_white.py 256.0.0.
ip[length] illegal. Program Exit!
$./add_white.py AFDAFDA
ip[length] illegal. Program Exit!
$./add_white.py A.A.A.A
Ip[is not a number] illegal. Program Exit!
$./add_white.py 192.1.1
ip[length] illegal. Program Exit!
$./add_white.py 192.168.1.2
The Add IP [' 192.168.1.2 '] add in white list ok~
]$./add_white.py 192.168.1.2
The Add IP [' 192.168.1.2 '] is in white list.
Writing is relatively simple, there is a wrong place to welcome the Exchange ~
This article is from the "end of the school" blog, please be sure to keep this source http://dyc2005.blog.51cto.com/270872/1943298
Python script simply detects IP legitimacy and adds to whitelist files