您的位置:首页 > 编程语言 > Python开发

python脚本简单检测ip合法性并添加到白名单文件

2017-06-29 22:32 1746 查看
一、功能说明
有时候项目需要通过ip地址来判定是否允许访问,通常通过一个白名单地址文件来存放这些允许放行的ip,但每次打开文件编辑比较麻烦,容易出错,也不知道是否添加过,故用python写了一个自动添加白名单的脚本。

二、脚本内容
#!/usr/bin/env python
#coding:utf-8
#2017-06-09 ver:1.0
import sys
white_list="white_list.txt"
add_ip=sys.argv[1].strip()
checkIp=add_ip.split('.')
if len(checkIp)!= 4:
print("ip[长度]不合法.程序退出!")
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[不是数字]不合法.程序退出!")
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[数字范围]不合法.程序退出!")
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()


三、执行结果
$ ./add_white.py 192.168.1.256
ip[数字范围]不合法.程序退出!
$ ./add_white.py 256.0.0..
ip[长度]不合法.程序退出!
$ ./add_white.py afdafda
ip[长度]不合法.程序退出!
$ ./add_white.py a.a.a.a
ip[不是数字]不合法.程序退出!
$ ./add_white.py 192.1.1
ip[长度]不合法.程序退出!
$ ./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.

写的比较简单,有不当之处欢迎指正交流~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ip地址 自动 较检